from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic.edit import FormView
from django.views.generic.list import ListView

from newsreader.news.collection.forms import CollectionRuleBulkForm
from newsreader.news.collection.views.base import CollectionRuleViewMixin
from newsreader.utils.views import NavListMixin


class CollectionRuleListView(CollectionRuleViewMixin, NavListMixin, ListView):
    paginate_by = 50
    template_name = "news/collection/views/rules.html"
    context_object_name = "rules"


class CollectionRuleBulkView(NavListMixin, FormView):
    form_class = CollectionRuleBulkForm

    def get_redirect_url(self):
        return reverse("news:collection:rules")

    def get_success_url(self):
        return self.get_redirect_url()

    def get_form(self, form_class=None):
        if form_class is None:
            form_class = self.get_form_class()
        return form_class(self.request.user, **self.get_form_kwargs())

    def form_invalid(self, form):
        url = self.get_redirect_url()

        messages.error(self.request, _("The form contains errors, try again later"))

        return redirect(url)


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

        for rule in form.cleaned_data["rules"]:
            rule.enabled = True
            rule.save()

        return response


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

        for rule in form.cleaned_data["rules"]:
            rule.enabled = False
            rule.save()

        return response


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

        for rule in form.cleaned_data["rules"]:
            rule.delete()

        return response
