from oscar.apps.dashboard.catalogue import forms as base_forms
from django import forms
from apps.catalogue.helpers import get_category_templates
from oscar.core.loading import get_model

Option = get_model('catalogue', 'Option')
ProductClass = get_model('catalogue', 'ProductClass')


class ProductClassForm(base_forms.ProductClassForm):
    class Meta(base_forms.ProductClassForm.Meta):
        model = ProductClass
        fields = ['name', 'requires_shipping', 'track_stock', 'front_end_view', 'options']


class CategoryForm(base_forms.CategoryForm):
    template = forms.ChoiceField(choices=get_category_templates, widget=forms.Select,
                                 required=False)

    class Meta(base_forms.CategoryForm.Meta):
        fields = ['name', 'description', 'image', 'template']


class OptionForm(forms.ModelForm):
    class Meta:
        fields = ['name', 'type', 'display_type']
        model = Option


class ProductAttributesForm(base_forms.ProductAttributesForm):
    class Meta(base_forms.ProductAttributesForm.Meta):
        fields = ["name", "code", "type", "option_group", "required", "use_for_variations", "display", "use_for_filter"]


class ProductCategoryForm(base_forms.ProductCategoryForm):
    primary = forms.BooleanField(required=False, widget=forms.CheckboxInput)

    class Meta(base_forms.ProductCategoryForm.Meta):
        fields = ['category', 'primary']


class ProductForm(base_forms.ProductForm):
    """
    Replacing the product form from oscar to display only the variable attributes for the child products
    """

    class Meta(base_forms.ProductForm.Meta):
        fields = ['title', 'upc', 'description', 'is_discountable', 'structure', 'subscription', 'featured',
                  'shipping_weight', 'strike_price','live', 'loyalty_points',
                  'label', 'label_drip']

    def add_attribute_fields(self, product_class, is_parent=False):
        """
        For each attribute specified by the product class, this method
        dynamically adds form fields to the product form.
        """
        if self.instance.parent:
            attributes = product_class.attributes.filter(use_for_variations=True).all()
        else:
            attributes = product_class.attributes.all()
        for attribute in attributes:
            field = self.get_attribute_field(attribute)
            if field:
                self.fields['attr_%s' % attribute.code] = field
                if attribute.type == 'date':
                    self.fields['attr_%s' % attribute.code].widget = forms.DateInput(attrs={'data-oscarWidget': 'date'})
                    self.fields['attr_%s' % attribute.code].input_formats = ['%y-%m-%d']
                # Attributes are not required for a parent product
                if is_parent:
                    self.fields['attr_%s' % attribute.code].required = False
