from django.conf import settings
from django.urls import reverse_lazy
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.list import ListView

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


class NewsView(NavListMixin, TemplateView):
    template_name = "news/core/views/homepage.html"

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

        return {
            **context,
            "homepageSettings": {
                "feedUrl": reverse_lazy("news:collection:feed-update", args=(0,)),
                "categoriesUrl": reverse_lazy("news:core:category-update", args=(0,)),
                "timezone": settings.TIME_ZONE,
                "autoMarking": self.request.user.auto_mark_read,
            },
        }


class CategoryViewMixin(NavListMixin):
    queryset = Category.objects.prefetch_related("rules").order_by("name")

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


class CategoryDetailMixin:
    success_url = reverse_lazy("news:core:categories")
    form_class = CategoryForm

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

        rules = CollectionRule.objects.filter(user=self.request.user).order_by("name")
        context_data["rules"] = rules

        return context_data

    def get_form_kwargs(self):
        return {**super().get_form_kwargs(), "user": self.request.user}


class CategoryListView(CategoryViewMixin, ListView):
    template_name = "news/core/views/categories.html"
    context_object_name = "categories"

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

        return {
            **context,
            "categories_create_url": reverse_lazy("news:core:category-create"),
            "categories_update_url": (
                reverse_lazy("news:core:category-update", args=(0,))
            ),
        }


class CategoryUpdateView(CategoryViewMixin, CategoryDetailMixin, UpdateView):
    template_name = "news/core/views/category-update.html"
    context_object_name = "category"


class CategoryCreateView(CategoryViewMixin, CategoryDetailMixin, CreateView):
    template_name = "news/core/views/category-create.html"
