from django import forms
from django.forms.widgets import CheckboxSelectMultiple

from newsreader.accounts.models import User
from newsreader.news.collection.models import CollectionRule
from newsreader.news.core.models import Category


class RulesWidget(CheckboxSelectMultiple):
    template_name = "news/core/widgets/rules.html"
    option_template_name = "news/core/widgets/rule.html"

    def create_option(self, *args, **kwargs):
        option = super().create_option(*args, **kwargs)

        # see https://docs.djangoproject.com/en/3.1/releases/3.1/#id1
        try:
            pk = int(option["value"])
        except TypeError:
            pk = option["value"].value

        instance = self.choices.queryset.get(pk=pk)

        if self.category and instance.category:
            option["selected"] = self.category.pk == instance.category.pk
        return {**option, "instance": instance}


class CategoryForm(forms.ModelForm):
    rules = forms.ModelMultipleChoiceField(
        required=False, queryset=CollectionRule.objects.none(), widget=RulesWidget
    )

    user = forms.ModelChoiceField(
        queryset=User.objects.none(),
        widget=forms.widgets.HiddenInput(attrs={"readonly": True}),
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")

        super().__init__(*args, **kwargs)

        self.fields["rules"].queryset = CollectionRule.objects.filter(user=self.user)
        self.fields["rules"].widget.category = self.instance

        self.fields["user"].queryset = User.objects.filter(pk=self.user.pk)

        self.initial["user"] = self.user

    def save(self, commit=True):
        instance = super().save(commit=False)

        if commit:
            instance.save()
            self.save_m2m()

        rule_ids = self.cleaned_data.get("rules", [])
        instance.rules.set(rule_ids)

        return instance

    class Meta:
        model = Category
        fields = ("name", "rules", "user")
