from django import forms
from .models import Tag, is_valid_area


class TagForm(forms.ModelForm):
    COORD_KEYS = ['topleft_x', 'topleft_y', 'bottomright_x', 'bottomright_y']

    class Meta:
        model = Tag
        fields = ['text', 'topleft_x', 'topleft_y', 'bottomright_x', 'bottomright_y']
        widgets = {
            'topleft_x': forms.HiddenInput(),
            'topleft_y': forms.HiddenInput(),
            'bottomright_x': forms.HiddenInput(),
            'bottomright_y': forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        self.factor_to_original = kwargs.pop('factor_to_original')
        super(TagForm, self).__init__(*args, **kwargs)

    def __get_area_value__(self, key):
        if len(self.data):
            rv = self.data.get(key)
        else:
            rv = self.get_initial_for_field(self.fields[key], key)
        try:
            return int(rv)
        except TypeError:
            return None
        except ValueError:
            return None

    @property
    def value_tl_x(self):
        return self.__get_area_value__('topleft_x')

    @property
    def value_tl_y(self):
        return self.__get_area_value__('topleft_y')

    @property
    def value_br_x(self):
        return self.__get_area_value__('bottomright_x')

    @property
    def value_br_y(self):
        return self.__get_area_value__('bottomright_y')

    @property
    def has_valid_coordinates(self):
        return is_valid_area(self.value_br_x, self.value_br_y, self.value_tl_x, self.value_tl_y)

    def save(self, commit=True):
        if self.has_valid_coordinates:
            self.instance.topleft_x = self.value_tl_x
            self.instance.topleft_y = self.value_tl_y
            self.instance.bottomright_x = self.value_br_x
            self.instance.bottomright_y = self.value_br_y
        else:
            self.instance.topleft_x = None
            self.instance.topleft_y = None
            self.instance.bottomright_x = None
            self.instance.bottomright_y = None
        return forms.ModelForm.save(self, commit=commit)
