# # coding=utf-8
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from .models import *


class RouteForm(forms.ModelForm):
    from_address_point_txt = forms.CharField(required=True)
    to_address_point_txt = forms.CharField(required=True)
    class Meta:
        model = Route
        exclude = [
            'name', 'name_plural', 'order', 'createDT', 'modifiedDT', 'enable', 'json_data',
            'receive_msg_by_sms', 'owner', 'owner_type'
        ]

    def clean(self):
        # print('check')
        cleaned_data = super(RouteForm, self).clean()



        try:

            if 'phone' in cleaned_data and 'phone' in cleaned_data:
                from BaseModels.validators.form_field_validators import get_phone_valid_error
                error = get_phone_valid_error(cleaned_data["phone"])
                if error:
                    self.add_error('phone', error)

            if 'extra_phone' in cleaned_data and 'extra_phone' in cleaned_data:
                from BaseModels.validators.form_field_validators import get_phone_valid_error
                error = get_phone_valid_error(cleaned_data["extra_phone"])
                if error:
                    self.add_error('extra_phone', error)

            if 'departure_DT' in cleaned_data and 'arrival_DT' in cleaned_data and cleaned_data['arrival_DT'] < cleaned_data['departure_DT']:
                self.add_error('arrival_DT', _('Указана неверная дата прибытия'))


            if 'from_place' in self.data and self.data['from_place'] not in [item[0] for item in self.fields['from_place'].choices]:
                cleaned_data['from_place'] = self.fields['from_place'].choices[0][0]
                if 'from_place' in self.errors and self.errors['from_place'].data[0].code == 'invalid_choice':
                    del self.errors['from_place']
            if 'to_place' in self.data and self.data['to_place'] not in [item[0] for item in self.fields['to_place'].choices]:
                cleaned_data['to_place'] = self.fields['to_place'].choices[0][0]
                if 'to_place' in self.errors and self.errors['to_place'].data[0].code == 'invalid_choice':
                    del self.errors['to_place']
            if 'cargo_type' in self.data and self.data['cargo_type'] not in [item[0] for item in self.fields['cargo_type'].choices]:
                cleaned_data['cargo_type'] = self.fields['cargo_type'].choices[0][0]
                if 'cargo_type' in self.errors and self.errors['cargo_type'].data[0].code == 'invalid_choice':
                    del self.errors['cargo_type']

        except Exception as e:
            print(str(e))

        # 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 RegistrationForm(forms.Form):
#     type_transport = forms.ChoiceField(choices=type_transport_choices, initial='avia', required=True, label='Выберите способ перевозки')
#     departure_DT = forms.DateTimeField(required=True, label='Дата и время выезда')
#     arrival_DT = forms.DateTimeField(required=True, label='Дата и время прибытия')
#     from_country = forms.CharField(required=True, label='Пункт выезда')
#     to_country = forms.CharField(required=True, label='Пункт приезда')
#     # from_city = forms.CharField(required=True)
#     # to_city = forms.CharField(required=True)
#     from_place = forms.ChoiceField(choices=transfer_location_choices, initial='other', required=True, label='Откуда можете забрать?')
#     to_place = forms.ChoiceField(choices=transfer_location_choices, initial='other', required=True, label='Куда можете доставить?')
#     cargo_type = forms.ChoiceField(choices=cargo_type_choices, initial='parcel', required=True, label='Могу перевезти')
#     weight = forms.IntegerField(required=True, label='Укажите вес до (кг)')
#     phone = forms.CharField(required=True, label='Укажите номер для связи')
#     add_phone = forms.CharField(required=True, label='Дополнительный номер')
#     receive_msg_by_email = forms.BooleanField(initial=False, required=True, label='Получать уведомления по E-mail')
#     # receive_msg_by_sms = forms.BooleanField(initial=False, required=True)
#     # owner = forms.IntegerField(required=True)
