from django.core.cache import cache
from django.urls import reverse_lazy
from django.views.generic.edit import FormView, ModelFormMixin

from newsreader.accounts.forms import UserSettingsForm
from newsreader.accounts.models import User
from newsreader.utils.views import NavListMixin


class SettingsView(NavListMixin, ModelFormMixin, FormView):
    template_name = "accounts/views/settings.html"
    success_url = reverse_lazy("accounts:settings:home")
    form_class = UserSettingsForm
    model = User

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().get(request, *args, **kwargs)

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

        return {
            **context,
            "favicon_task_allowed": not cache.get(f"{self.request.user}-favicon-task"),
        }

    def get_object(self, **kwargs):
        return self.request.user

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