from django import forms

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


class CollectionRuleForm(forms.ModelForm):
    category = forms.ModelChoiceField(required=False, queryset=Category.objects.all())

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

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

        self.fields["category"].queryset = Category.objects.filter(user=self.user)

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

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

        return instance

    class Meta:
        model = CollectionRule
        fields = "__all__"
