import datetime
from django.utils import timezone
from django.views import generic
from podcasts.models import Podcast, PodcastEpisode

from scrobbles.models import Scrobble
from scrobbles.views import (
    ScrobbleableListView,
    ScrobbleableDetailView,
    ChartContextMixin,
)


class PodcastListView(ScrobbleableListView):
    model = PodcastEpisode
    template_name = "podcasts/podcast_list.html"

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        user = self.request.user
        now = timezone.now()
        start_day_of_week = now - datetime.timedelta(days=now.weekday())
        start_day_of_month = now.replace(day=1)

        scrobbles_this_week = Scrobble.objects.filter(
            user=user,
            podcast_episode__isnull=False,
            timestamp__gte=start_day_of_week,
        ).select_related("podcast_episode", "podcast_episode__podcast")

        scrobbles_this_month = Scrobble.objects.filter(
            user=user,
            podcast_episode__isnull=False,
            timestamp__gte=start_day_of_month,
        ).select_related("podcast_episode", "podcast_episode__podcast")

        podcasts_this_week = {}
        for scrobble in scrobbles_this_week:
            podcast = scrobble.podcast_episode.podcast
            if podcast:
                podcasts_this_week[podcast.id] = {
                    "podcast": podcast,
                    "count": podcasts_this_week.get(podcast.id, {}).get("count", 0) + 1,
                }

        podcasts_this_month = {}
        for scrobble in scrobbles_this_month:
            podcast = scrobble.podcast_episode.podcast
            if podcast:
                podcasts_this_month[podcast.id] = {
                    "podcast": podcast,
                    "count": podcasts_this_month.get(podcast.id, {}).get("count", 0)
                    + 1,
                }

        context_data["podcasts_this_week"] = sorted(
            podcasts_this_week.values(), key=lambda x: x["count"], reverse=True
        )
        context_data["podcasts_this_month"] = sorted(
            podcasts_this_month.values(),
            key=lambda x: x["count"],
            reverse=True,
        )

        return context_data


class PodcastDetailView(ChartContextMixin, generic.DetailView):
    model = Podcast
    slug_field = "uuid"

    def get_context_data(self, **kwargs):
        user = self.request.user
        context_data = super().get_context_data(**kwargs)
        context_data["scrobbles"] = self.object.scrobbles(user)
        return context_data
