import datetime

from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from scrobbles.models import Scrobble
from scrobbles.views import ScrobbleableDetailView, ScrobbleableListView
from webpages.forms import WebPageReadForm
from webpages.models import WebPage


class WebPageListView(ScrobbleableListView):
    model = WebPage

    def get_queryset(self):
        queryset = super().get_queryset()
        tag_name = self.request.GET.get("tag")
        if tag_name:
            from django.contrib.contenttypes.models import ContentType
            from taggit.models import TaggedItem
            ct = ContentType.objects.get_for_model(WebPage)
            webpages = TaggedItem.objects.filter(
                content_type=ct,
                tag__name__iexact=tag_name,
            ).values_list("object_id", flat=True)
            queryset = queryset.filter(pk__in=webpages)
        return queryset

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data["active_tag"] = self.request.GET.get("tag", "")
        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,
            web_page__isnull=False,
            timestamp__gte=start_day_of_week,
        ).select_related("web_page", "web_page__domain")

        scrobbles_this_month = Scrobble.objects.filter(
            user=user,
            web_page__isnull=False,
            timestamp__gte=start_day_of_month,
        ).select_related("web_page", "web_page__domain")

        domains_this_week = {}
        for scrobble in scrobbles_this_week:
            domain = scrobble.web_page.domain
            if domain:
                domains_this_week[domain.id] = {
                    "domain": domain,
                    "count": domains_this_week.get(domain.id, {}).get("count", 0) + 1,
                }

        domains_this_month = {}
        for scrobble in scrobbles_this_month:
            domain = scrobble.web_page.domain
            if domain:
                domains_this_month[domain.id] = {
                    "domain": domain,
                    "count": domains_this_month.get(domain.id, {}).get("count", 0) + 1,
                }

        domains_week_sorted = sorted(
            domains_this_week.values(), key=lambda x: x["count"], reverse=True
        )
        domains_month_sorted = sorted(
            domains_this_month.values(), key=lambda x: x["count"], reverse=True
        )

        domain_page = self.request.GET.get("domain_page", 1)

        context_data["domains_this_week"] = Paginator(domains_week_sorted, 10).page(
            domain_page
        )
        context_data["domains_this_month"] = Paginator(domains_month_sorted, 10).page(
            domain_page
        )
        context_data["domain_page"] = int(domain_page)
        context_data["domain_paginator"] = Paginator(domains_week_sorted, 10)

        return context_data


class WebPageDetailView(ScrobbleableDetailView):
    model = WebPage

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            latest = self.object.scrobbles(self.request.user).first()
            if latest:
                context["latest_scrobble_uuid"] = str(latest.uuid)
                notes = latest.log.get("notes", []) if latest.log else []
                context["latest_scrobble_notes"] = notes
                context["latest_scrobble_notes_html"] = latest.logdata.notes_as_html()
                context["article_length"] = (
                    len(self.object.extract) if self.object.extract else 0
                )
        return context


class WebPageReadView(LoginRequiredMixin, generic.edit.FormView, generic.DetailView):
    model = WebPage
    slug_field = "uuid"
    template_name = "webpages/webpage_read.html"
    form_class = WebPageReadForm

    def get(self, *args, **kwargs):
        user = self.request.user
        webpage = WebPage.objects.get(uuid=kwargs.get("slug"))
        latest_scrobble = webpage.scrobbles(user).last()
        if latest_scrobble.played_to_completion:
            redirect(reverse("webpages:webpage_detail", kwargs={"slug": webpage.uuid}))
        return super().get(*args, **kwargs)

    def form_valid(self, *args):
        user = self.request.user
        webpage = WebPage.objects.get(uuid=self.kwargs.get("slug"))
        latest_scrobble = webpage.scrobbles(user).last()
        if not latest_scrobble.played_to_completion:
            latest_scrobble.stop()

            latest_scrobble.log["notes"] = self.request.POST.get("notes")
            latest_scrobble.save(update_fields=["log"])

        return HttpResponseRedirect(webpage.url)
