from django import forms
from django.conf import settings
from django.utils.translation import ugettext as _
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth import authenticate
from django.contrib import messages
from .models import User
from django.contrib.auth.forms import AuthenticationForm


class RegisterForm(forms.ModelForm):
    phone_number = forms.IntegerField(required=True)
    password1 = forms.CharField(widget=forms.PasswordInput())
    password2 = forms.CharField(widget=forms.PasswordInput())
    post_code = forms.IntegerField()

    MIN_LENGTH = 4

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'post_code',
                  'town_city', 'phone_number', 'address_line_1', 'address_line_2', 'is_active', 'is_staff', 'is_superuser', 'password1', 'password2']

    def clean_username(self):
        username = self.data.get('username')
        return username

    def clean_password(self):
        self.data.get('password1')
        validate_password(password)
        if password != self.data.get('password2'):
            raise forms.ValidationError(
                _("Passwords do not match"), code='invalid')
        return password

    def clean_phone_number(self):
        phone_number = self.data.get('phone_number')
        if User.objects.filter(phone_number=phone_number).exists():
            raise forms.ValidationError(
                _("Another user with this phone number already exists"), code='invalid')
        if len(phone_number) != 10:
            raise forms.ValidationError(
                _("Phone number is must be a valid format"), code='invalid')
        else:
            return phone_number

    def clean_password1(self):
        password1 = self.data.get('password1')
        password2 = self.data.get('password2')

        if password1 != password2:
            raise forms.ValidationError(
                _("Password must match"), code="invalid")
        else:
            return password1

    def save(self, *args, **kwargs):
        user = super(RegisterForm, self).save(*args, **kwargs)
        user.set_password(self.cleaned_data['password1'])
        user.save()
        return user
