from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, DateField
from wtforms.validators import DataRequired, Length, ValidationError, Email, Optional
from minibase.database.models import Person
import minibase.database.utils as dbUtils


# Defines the form class to be used for the user registretion
class personForm(FlaskForm):
    # Decalarion of the fields for the form and it's propereties
    name = StringField('Name', validators=[DataRequired(), Length(min=3, max=20)])
    last_name = StringField('Last Name', validators=[DataRequired(), Length(min=3, max=20)])
    date_of_birth = DateField('Birth Date')
    company = SelectField('Company', validators=[DataRequired()])
    competence = SelectField('Competence', validators=[DataRequired()])
    role = SelectField('Role', validators=[DataRequired()])
    mail_prof = StringField('Email Professional', validators=[DataRequired(), Email()])
    mail_priv = StringField('Email Private', validators=[Optional(), Email()])
    tel_prof_fix = StringField('Tel Professional Fix', validators=[Optional()])
    tel_prof_mobile = StringField('Tel Professional Mob', validators=[Optional()])
    tel_priv_fix = StringField('Tel Private Fix', validators=[Optional()])
    tel_priv_mobile = StringField('Tel Private Mob', validators=[Optional()])
    submit = SubmitField('Register Person')

    # Queries to be made in order to validate the form : If person with this  name exitst within the same company
    # Case Insensistive
    def validate_person(self):
        person_query = Person.query.filter(Person.name.ilike(self.name.data))  # Database Querry ilike means case insessitive
        for person in person_query:
            if person.name:
                if person.last_name.lower() == self.last_name.data.lower():
                    if person.company == self.company.data:
                        raise ValidationError('This person working in this company already exist')
