import json

from zoneinfo import available_timezones

from django.urls import reverse_lazy

from django_celery_beat.models import IntervalSchedule, PeriodicTask

from newsreader.news.collection.models import CollectionRule
from newsreader.news.core.models import Category
from newsreader.utils.views import NavListMixin


class CollectionRuleViewMixin(NavListMixin):
    queryset = CollectionRule.objects.order_by("name")

    def get_queryset(self):
        user = self.request.user
        return self.queryset.filter(user=user)


class CollectionRuleDetailMixin:
    success_url = reverse_lazy("news:collection:rules")

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)

        categories = Category.objects.filter(user=self.request.user).order_by("name")
        timezones = available_timezones()

        context_data["categories"] = categories
        context_data["timezones"] = timezones

        return context_data

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user
        return kwargs


class TaskCreationMixin:
    def form_valid(self, form):
        response = super().form_valid(form)

        interval, period = self.task_interval
        task_interval, _ = IntervalSchedule.objects.get_or_create(
            every=interval, period=period
        )

        PeriodicTask.objects.get_or_create(
            name=f"{self.request.user.email}-{self.task_name}",
            task=self.task_type,
            defaults={
                "args": json.dumps([self.request.user.pk]),
                "interval": task_interval,
                "enabled": True,
            },
        )

        return response
