from datetime import datetime, time
import logging

from django.db import transaction
from django.utils import timezone as tz

from aircox.models import Diffusion, Schedule

logger = logging.getLogger("aircox.commands")


__all__ = ("DiffusionMonitor",)


class DiffusionMonitor:
    """Handle generation and update of Diffusion instances."""

    date = None

    def __init__(self, date):
        self.date = date or date.today()

    def update(self):
        episodes, diffusions = [], []
        for schedule in Schedule.objects.filter(program__active=True, initial__isnull=True):
            eps, diffs = schedule.diffusions_of_month(self.date)
            if eps:
                episodes += eps
            if diffs:
                diffusions += diffs

            logger.info(
                "[update] %s: %d episodes, %d diffusions and reruns",
                str(schedule),
                len(eps),
                len(diffs),
            )

        with transaction.atomic():
            logger.info(
                "[update] save %d episodes and %d diffusions",
                len(episodes),
                len(diffusions),
            )
            for episode in episodes:
                episode.save()
            for diffusion in diffusions:
                # force episode id's update
                diffusion.episode = diffusion.episode
                diffusion.save()

    def clean(self):
        qs = Diffusion.objects.filter(
            type=Diffusion.TYPE_UNCONFIRMED,
            start__lt=tz.make_aware(datetime.combine(self.date, time.min)),
        )
        logger.info("[clean] %d diffusions will be removed", qs.count())
        qs.delete()
