from flask import render_template, url_for, flash, redirect, request, Blueprint
from minibase import db
from minibase.config import themeMinibase, globalVars
from minibase.database.models import Person
from minibase.person.forms import personForm
import minibase.database.utils as dbUtils

# Declaring a blueprint
person = Blueprint('person', __name__)


@person.route("/person_register", methods=['GET', 'POST'])
def person_register():
    form = personForm()
    form.company.choices = [(row.id, row.name) for row in dbUtils.getCompanies()]
    form.competence.choices = [(row.id, row.name) for row in dbUtils.getPersonCompetences()]
    form.role.choices = [(row.id, row.name) for row in dbUtils.getPersonRoles()]
    if form.validate_on_submit():
        person = Person(
            name=form.name.data,
            last_name=form.last_name.data,
            date_of_birth=form.date_of_birth.data,
            tel_prof_fix=form.tel_prof_fix.data,
            tel_prof_mobile=form.tel_prof_mobile.data,
            tel_priv_fix=form.tel_priv_fix.data,
            tel_priv_mobile=form.tel_priv_mobile.data,
            mail_prof=form.mail_prof.data,
            mail_priv=form.mail_priv.data,
            company_id=form.company.data,
            country_id=dbUtils.getCompanyCountryId(form.company.data),
            state=dbUtils.getCompanyState(form.company.data),
            city=dbUtils.getCompanyCity(form.company.data),
            post_code=dbUtils.getCompanyPostCode(form.company.data),
            street_name=dbUtils.getCompanyStreetName(form.company.data),
            street_no=dbUtils.getCompanyStreetNo(form.company.data),
            role_id=form.role.data,
            competence_id=form.competence.data)

        db.session.add(person)
        db.session.commit()

        flash(f'{"Person succesfull registered!"}', 'success')
        return render_template('register_form.html',
                            title='Register Person',
                            theme=themeMinibase,
                            globalVars=globalVars,
                            form=form)

    return render_template('register_form.html',
                            title='Register Person',
                            theme=themeMinibase,
                            globalVars=globalVars,
                            form=form)
