from email.policy import default
from dal import autocomplete

from django import forms

from .models import CategoryTag, Product


class ProductTagForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('__all__')
        widgets = {
            'category': autocomplete.TagSelect2(url='category-tag-autocomplete')
        }

class CategoryTagForm(forms.ModelForm):
    name = forms.CharField(required=False, disabled=True)
    parent_category = autocomplete.Select2ListCreateChoiceField(required=False, widget=autocomplete.Select2(url='category-tag-autocomplete', attrs={"data-tags": "true"}))
    class Meta:
        model = CategoryTag
        fields = ('name', 'label', 'slug', 'parent_category', 'official', 'image')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.id:
            project_name_field = self.fields['parent_category']
            parent_category = self.instance.parent
            project_name_field.initial = parent_category
            project_name_field.choices = [(parent_category, parent_category)]


    def save(self, commit=True):
        parent_name = self.cleaned_data.get('parent_category', None)
        prefix = ''
        if parent_name:
            prefix = parent_name + '/'
        self.instance.name =  prefix + self.instance.label
        return super(CategoryTagForm, self).save(commit=commit)