import logging
from django import forms

from core import OrderStatus
from core.models import (
    ProductVariant,
    Order,
    OrderLine,
    ShippingRate,
    TrackingNumber,
    Coupon,
    ProductPhoto
)

logger = logging.getLogger(__name__)


class ProductVariantUpdateForm(forms.ModelForm):
    class Meta:
        model = ProductVariant
        fields = [
            'name',
            'sku',
            'price',
            'weight',
            'visible_in_listings',
            'track_inventory',
            'stock',
            'sorting',
            'image'
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance:
            self.fields['image'].queryset = ProductPhoto.objects.filter(
                product=self.instance.product
            )

    def clean_weight(self):
        data = self.cleaned_data['weight']
        if not data:
            data = 0

        return data


class CouponForm(forms.ModelForm):
    class Meta:
        model = Coupon
        fields = (
            'type',
            'name',
            'code',
            'valid_from',
            'valid_to',
            'discount_value_type',
            'discount_value',
            'variants',
        )
        widgets = {
            'valid_from': forms.DateInput(attrs={
                'type': 'date'
            }),
            'valid_to': forms.DateInput(attrs={
                'type': 'date'
            }),
        }


class OrderLineFulfillForm(forms.ModelForm):
    # send_shipment_details_to_customer = forms.BooleanField(initial=True)

    class Meta:
        model = OrderLine
        fields = ('quantity_fulfilled',)
        widgets = {
            'quantity_fulfilled': forms.NumberInput(attrs={
                'min': 0,
            })
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['quantity_fulfilled'].widget.attrs['max'] = self.instance.quantity


OrderLineFormset = forms.inlineformset_factory(
    Order, OrderLine, form=OrderLineFulfillForm,
    extra=0, can_delete=False
)


class OrderCancelForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('status',)
        widgets = {
            'status': forms.HiddenInput()
        }


class OrderTrackingForm(forms.ModelForm):
    # send_shipment_details_to_customer = forms.BooleanField(initial=True)

    class Meta:
        model = TrackingNumber
        fields = ['tracking_id']
        labels = {
            'tracking_id': 'Tracking Number'
        }


OrderTrackingFormset = forms.inlineformset_factory(
    Order, TrackingNumber, form=OrderTrackingForm,
    extra=1, can_delete=False
)


class ProductPhotoForm(forms.ModelForm):
    class Meta:
        model = ProductPhoto
        fields = ('image',)
