from iso3166 import countries
import string
import random

from models import User, Role

from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, DecimalField
from wtforms import validators, ValidationError
from wtforms.fields import EmailField

class EditProfileForm(FlaskForm):
    name = StringField('Name:', [validators.DataRequired(), validators.Length(3, 60)])
    address = StringField('Address:', [validators.DataRequired(), validators.Length(2, 50)])
    city = StringField('City:', [validators.DataRequired(), validators.Length(2,40)])

    postcode = StringField('Postcode:')

    clist = []
    for c in countries:
        clist.append((c.alpha2, c.name))
    country = SelectField('Country:', choices=clist, default='BG')

    phone = StringField('Phone:')
    twofactor = BooleanField('Enable 2-factor authentication')
    submit = SubmitField('Update')

class EditProfileAdminForm(FlaskForm):
    email = StringField('Електроннa поща (логин):', [validators.DataRequired(), validators.Length(1, 64), validators.Email()])
    confirmed = BooleanField('Activated')
    role = SelectField('Role', coerce=int)

    name = StringField('Лице за контакт:', [validators.DataRequired(), validators.Length(3, 60)])
    address = StringField('Адрес:', [validators.DataRequired(), validators.Length(2, 50)])
    city = StringField('Град:', [validators.DataRequired(), validators.Length(2,40)])
    postcode = DecimalField('Пощенски Код:')

    clist = []
    for c in countries:
        clist.append((c.alpha2, c.name))
    country = SelectField('Държава:', choices=clist)

    phone = DecimalField('Телефон:', [validators.DataRequired()])
    twofactor = BooleanField('2-factor authentication')
    submit = SubmitField('Обнови')

    def __init__(self, user, *args, **kwargs):
        super(EditProfileAdminForm, self).__init__(*args, **kwargs)
        self.role.choices = [(role.id, role.name)
                             for role in Role.query.order_by(Role.name).all()]
        self.user = user

    def validate_email(self, field):
        if field.data != self.user.email and User.query.filter_by(email=field.data).first():
            raise ValidationError('Email-а е вече регистриран.')


