# coding=utf-8
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from .models import *
# from djng.styling.bootstrap3.forms import Bootstrap3ModelForm
# from djng.forms import fields, NgModelFormMixin, NgFormValidationMixin, NgModelForm
# from datetimepicker.widgets import DateTimePicker
# from datetimepicker.helpers import js_loader_url



# class PersonForm(NgModelFormMixin, NgFormValidationMixin, NgModelForm, Bootstrap3ModelForm):
#
#     form_name = 'person_form'
#     scope_prefix = 'person_data'
#
#     class Meta:
#         model = UserProfile
#         fields = ['name', 'departament', 'company', 'company_position',
#                   'days_to_order_cancellation_default', 'days_to_pay_default',
#                   'pay_terms', 'birthdate',
#                   'phone', 'email', 'discount', 'document_sign_person']



def emailValid(value):
    if User.objects.filter(username=value, is_active=True):
        raise ValidationError(_(u'пользователь с таким e-mail уже существует, воспользуйтесь восстановлением пароля'))

def check_authorizationBy_cleaned_data(cleaned_data):
    from django.contrib.auth import authenticate
    print('check_authorizationBy_cleaned_data')
    username = cleaned_data.get('username')
    password = cleaned_data.get('password')

    user = authenticate(username=username, password=password)
    # print(user)
    if user:
    #     if user.is_active:
        return user

def check_activate_by_user(reg_user):
    print('check_activate_by_user')
    if reg_user:
        if reg_user.is_active:
            return True

    return False

class LoginForm(AuthenticationForm):
    username = forms.EmailField(label=_('Email'), widget=forms.TextInput())
    password = forms.CharField(min_length=8, label=_('Пароль'), widget=forms.PasswordInput(render_value=False))

    def clean(self):
        # print('check')
        cleaned_data = super(LoginForm, self).clean()
        reg_user = check_authorizationBy_cleaned_data(cleaned_data)
        # print(reg_user)
        if not reg_user:
            raise ValidationError(_(u'Пользователь с введенными регистрационными данными не зарегистрирован. Проверьте правильность ввода e-mail и пароля.'))
        else:
            if not check_activate_by_user(reg_user):
                raise ValidationError(_(u'Указанная учетная запись не была Активирована'))
        return cleaned_data


class ResetPassword_byEmail_Form(AuthenticationForm):
    email = forms.EmailField(label=_('Email'), widget=forms.TextInput())