from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from easy_thumbnails.files import get_thumbnailer

from aircox.conf import settings

from .page import Page
from .program import ProgramChildQuerySet

__all__ = ("Episode",)


class Episode(Page):
    objects = ProgramChildQuerySet.as_manager()
    detail_url_name = "episode-detail"
    item_template_name = "aircox/widgets/episode_item.html"

    @property
    def program(self):
        return getattr(self.parent, "program", None)

    @cached_property
    def podcasts(self):
        """Return serialized data about podcasts."""
        from ..serializers import PodcastSerializer

        podcasts = [PodcastSerializer(s).data for s in self.sound_set.public().order_by("type")]
        if self.cover:
            options = {"size": (128, 128), "crop": "scale"}
            cover = get_thumbnailer(self.cover).get_thumbnail(options).url
        else:
            cover = None

        for index, podcast in enumerate(podcasts):
            podcasts[index]["cover"] = cover
            podcasts[index]["page_url"] = self.get_absolute_url()
            podcasts[index]["page_title"] = self.title
        return podcasts

    @program.setter
    def program(self, value):
        self.parent = value

    class Meta:
        verbose_name = _("Episode")
        verbose_name_plural = _("Episodes")

    def get_absolute_url(self):
        if not self.is_published:
            return self.program.get_absolute_url()
        return super().get_absolute_url()

    def save(self, *args, **kwargs):
        if self.parent is None:
            raise ValueError("missing parent program")
        super().save(*args, **kwargs)

    @classmethod
    def get_default_title(cls, page, date):
        return settings.EPISODE_TITLE.format(
            program=page,
            date=date.strftime(settings.EPISODE_TITLE_DATE_FORMAT),
        )

    @classmethod
    def get_init_kwargs_from(cls, page, date=None, title=None, **kwargs):
        """Get default Episode's title."""
        title = (
            settings.EPISODE_TITLE.format(
                program=page,
                date=date.strftime(settings.EPISODE_TITLE_DATE_FORMAT),
            )
            if title is None
            else title
        )
        return super().get_init_kwargs_from(page, title=title, program=page, **kwargs)
