from PIL import Image
from django import forms
from .models import Profile
from captcha.fields import ReCaptchaField
from django.contrib.auth.forms import AuthenticationForm


class AvatarForm(forms.ModelForm):
    avatar = forms.ImageField(widget=forms.FileInput(attrs={'class': ''}), label='Аватар', required=False)
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        model = Profile
        fields = ('avatar', 'x', 'y', 'width', 'height', )

    def save(self):
        instance = super(AvatarForm, self).save()
        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')
        image = Image.open(instance.avatar)
        cropped_image = image.crop((x, y, w+x, h+y))
        resized_image = cropped_image.resize((400, 400), Image.ANTIALIAS)
        resized_image.save(instance.avatar.path)

        return instance


class CaptchaLoginForm(AuthenticationForm):
    captcha = ReCaptchaField()

    class Meta:
        fields = ('login', 'password', 'captcha')
