from django.contrib import messages
from django.core.cache import cache
from django.urls import reverse_lazy
from django.utils.translation import gettext as _
from django.views.generic import RedirectView

from newsreader.news.collection.tasks import FaviconTask


class FaviconRedirectView(RedirectView):
    url = reverse_lazy("accounts:settings:home")

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)

        user = request.user
        task_active = cache.get(f"{user.email}-favicon-task")

        if not task_active:
            FaviconTask.delay(user.pk)
            messages.success(request, _("Favicons are being fetched"))
            cache.set(f"{user.email}-favicon-task", 1, 18000)  # 5 hours
            return response

        messages.error(request, _("Limit reached, try again later"))
        return response
