from django.contrib import messages
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic.edit import CreateView, FormView, UpdateView

from django_celery_beat.models import IntervalSchedule

from newsreader.news.collection.choices import RuleTypeChoices
from newsreader.news.collection.forms import FeedForm, OPMLImportForm
from newsreader.news.collection.models import CollectionRule
from newsreader.news.collection.views.base import (
    CollectionRuleDetailMixin,
    CollectionRuleViewMixin,
    TaskCreationMixin,
)
from newsreader.utils.opml import parse_opml
from newsreader.utils.views import NavListMixin


class FeedUpdateView(CollectionRuleViewMixin, CollectionRuleDetailMixin, UpdateView):
    template_name = "news/collection/views/feed-update.html"
    context_object_name = "feed"
    form_class = FeedForm

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(type=RuleTypeChoices.feed)


class FeedCreateView(
    CollectionRuleViewMixin, CollectionRuleDetailMixin, TaskCreationMixin, CreateView
):
    template_name = "news/collection/views/feed-create.html"
    task_interval = (1, IntervalSchedule.HOURS)
    task_name = "feed"
    task_type = "FeedTask"
    form_class = FeedForm


class OPMLImportView(NavListMixin, FormView):
    form_class = OPMLImportForm
    template_name = "news/collection/views/import.html"

    def form_valid(self, form):
        user = self.request.user
        file = form.cleaned_data["file"]
        skip_existing = form.cleaned_data["skip_existing"]

        instances = parse_opml(file, user, skip_existing=skip_existing)

        try:
            feeds = CollectionRule.objects.bulk_create(instances)
        except IOError:
            form.add_error("file", _("Invalid OPML file"))
            return self.form_invalid(form)

        if not feeds:
            form.add_error("file", _("No (new) feeds found"))
            return self.form_invalid(form)

        message = _(f"{len(feeds)} new feeds created")
        messages.success(self.request, message)

        return super().form_valid(form)

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