from flask import render_template, url_for, flash, redirect, request, Blueprint, session
from minibase import db
from minibase.config import themeMinibase, globalVars
from minibase.project.forms import selectProjectForm, projectUpdateForm, projectRegisterForm
from minibase.project.forms import selectElementForm, elementUpdateForm, elementRegisterForm
import minibase.database.utils as dbUtils
from minibase.database.models import Project, Project_element
# Declaring a blueprint
project = Blueprint('project', __name__)


@project.route("/select_project", methods=['GET', 'POST'])
def select_project():
    if globalVars.selectedCompany:  # If a company is sected
        form = selectProjectForm()
        form.project.choices = [(row.id, row.name) for row in dbUtils.getProjectOfSelectedCompany()]
        if form.validate_on_submit():
            dbUtils.setSelectedProject(form.project.data)
            if form.submit_to_element.data:  # To tertermin wjhic submit button was pressed 
                return redirect(url_for('project.select_element'))
            else:
                return redirect(url_for('project.show_project', projectId=form.project.data))

        return render_template('project/select_project.html',
                                title='Select Project Name for : ' + globalVars.selectedCompany.name,
                                theme=themeMinibase,
                                globalVars=globalVars,
                                form=form)
    else:
        flash(f'{"Please selecet a company first"}', 'warning')
        return redirect(url_for('company.select_company'))


@project.route("/show_project/<int:projectId>", methods=['GET', 'POST'])
def show_project(projectId):
    if projectId:  # If a company is sected
        form = projectUpdateForm()
        # I can't use  globalVars here for sqlAlchemy to be able to make a session an sql query must be made and returned
        project = dbUtils.getProject(projectId)
        image_file = url_for('static', filename='pics/' + project.image_file)
        notes = dbUtils.getSelectedProjectNotes()
        elements = dbUtils.getSelectedProjectElements()
        # To initiate choises as a list allow us to match it with the id's 
        form.responsible.choices = [(row.id, row.name +' '+row.last_name) for row in dbUtils.getEmployeesOfSelectedCompany()]
        form.status.choices = [(row.id, row.name) for row in dbUtils.getProjectStatuses()]
        form.industry.choices = [(row.id, row.name) for row in dbUtils.getIndustryNames()]

        if form.validate_on_submit():
            project.description = form.description.data
            project.industry_id = int(form.industry.data)
            project.status_id = int(form.status.data)
            project.owner_id = int(form.responsible.data)
            project.qte_prototype = form.qtePrototype.data
            project.qte_start = form.qteStart.data
            project.qte_production = form.qteProduction.data
            project.date_prototype = form.datePrototype.data
            project.date_start = form.dateStart.data
            project.date_production = form.dateProduction.data
            db.session.add(project)
            db.session.commit()
            flash(f'{"Project Updated"}', 'success')
            return redirect(url_for('project.show_project'))
        elif request.method == 'GET':
            form.responsible.data = str(project.owner_id)
            form.status.data = str(project.status.id)
            form.industry.data = str(project.industry_id)
            form.description.data = project.description
            form.qtePrototype.data = project.qte_prototype
            form.qteStart.data = project.qte_start
            form.qteProduction.data = project.qte_production
            form.datePrototype.data = project.date_prototype
            form.dateStart.data = project.date_start
            form.dateProduction.data = project.date_production

        return render_template('project/show_project.html',
                                title=project.belongs_to.name + ' : ' + project.name,
                                companyName=project.belongs_to.name,
                                projectName=project.name,
                                projectId=project.id,
                                notes=notes,
                                elements=elements,
                                image_file=image_file,
                                theme=themeMinibase,
                                globalVars=globalVars,
                                form=form)
    else:
        flash(f'{"Please selecet a project first"}', 'warning')
        return redirect(url_for('project.select_project'))


@project.route("/register_project", methods=['GET', 'POST'])
def register_project():
    form = projectRegisterForm()
    form.company.choices = [(row.id, row.name) for row in dbUtils.getCompanies()]
    form.status.choices = [(row.id, row.name) for row in dbUtils.getProjectStatuses()]
    form.industry.choices = [(row.id, row.name) for row in dbUtils.getIndustryNames()]

    if form.validate_on_submit():
        flash(f'{"Project Updated"}', 'success')
        project = Project(
            name=form.name.data,
            company_id=form.company.data,
            description=form.description.data,
            industry_id=form.industry.data,
            status_id=form.status.data,
            qte_prototype=form.qtePrototype.data,
            qte_start=form.qteStart.data,
            qte_production=form.qteProduction.data,
            date_prototype=form.datePrototype.data,
            date_start=form.dateStart.data,
            date_production=form.dateProduction.data)
        # Adds project to the database
        db.session.add(project)
        db.session.commit()
        # Prepares the globalVars for redirection. 
        dbUtils.setSelectedCompany(form.company.data)
        projectId = dbUtils.getProjectId(globalVars.selectedCompany.id, form.name.data)
        # Prepares the globalVars for redirection. 
        dbUtils.setSelectedProject(projectId)
        flash(f'{"Project Registered"}', 'success')
        # Wihtout the selectedProject and selectedCompny Varibale the redirect would give an error 
        return redirect(url_for('project.show_project'))

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


@project.route("/select_element", methods=['GET', 'POST'])
def select_element():
    if globalVars.selectedProject:  # If a project is sected
        form = selectElementForm()
        form.element.choices = [(row.id, row.name) for row in dbUtils.getSelectedProjectElements()]
        if form.validate_on_submit():
            dbUtils.setSelectedElement(form.element.data)
            return redirect(url_for('project.show_element', elementId=form.element.data))

        return render_template('project/select_element.html',
                                title='Select Project Element for : ' + globalVars.selectedProject.name,
                                theme=themeMinibase,
                                globalVars=globalVars,
                                form=form)
    else:
        flash(f'{"Please selecet a project"}', 'warning')
        return redirect(url_for('project.select_project'))


@project.route("/show_element/<int:elementId>", methods=['GET', 'POST'])
def show_element(elementId):
    if elementId: # If a company is sected
        form = elementUpdateForm()
        element = dbUtils.getElement(elementId)
        form.status.choices = [(row.id, row.name) for row in dbUtils.getProjectStatuses()]
        form.company_to_ship.choices = [(row.id, row.name) for row in dbUtils.getCompanies()]
        form.owner.choices = [(row.id, row.name + ' ' + row.last_name) for row in dbUtils.getCompanyEmployees(element.project.id)]

        if form.validate_on_submit():
            element.description = form.description.data
            element.qte_per_project = form.qtePerProject.data
            element.status_id = form.status.data
            element.company_ship_to_id = form.company_to_ship.data
            element.owner_id = form.owner.data
            db.session.add(element)
            db.session.commit()
            flash(f'{"Element Updated"}', 'success')
            return redirect(url_for('project.show_element', elementId=element.id))
        elif request.method == 'GET':
            form.description.data = element.description
            form.qtePerProject.data = element.qte_per_project
            form.status.data = str(element.status_id)
            form.company_to_ship.data = str(element.company_ship_to_id)
            form.owner.data = str(element.owner_id)
            return render_template('register_form.html',
                                    title=element.name,
                                    theme=themeMinibase,
                                    globalVars=globalVars,
                                    form=form)

        return render_template('register_form.html',
                                title=element.name,
                                theme=themeMinibase,
                                globalVars=globalVars,
                                form=form)
    else:
        flash(f'{"Element Id is missing"}', 'warning')
        return redirect(url_for('project.show_project'))

@project.route("/register_element", methods=['GET', 'POST'])
def register_element():
    if globalVars.selectedCompany: # If a company is sected
        form = elementRegisterForm()
        form.project.choices = [(row.id, row.name) for row in dbUtils.getProjectOfSelectedCompany()]
        form.status.choices = [(row.id, row.name) for row in dbUtils.getProjectStatuses()]
        form.company_to_ship.choices = [(row.id, row.name) for row in dbUtils.getCompanies()]
        form.owner.choices = [(row.id, row.name + ' ' + row.last_name) for row in dbUtils.getCompanyEmployees(globalVars.selectedCompany.id)]

        if form.validate_on_submit():
            element = Project_element(
                project_id=form.project.data,
                name=form.name.data,
                description=form.description.data,
                qte_per_project=form.qtePerProject.data,
                status_id=form.status.data,
                company_ship_to_id=form.company_to_ship.data,
                owner_id=form.owner.data)
            db.session.add(element)
            db.session.commit()
            dbUtils.setSelectedProject(form.project.data)
            elementId = dbUtils.getElementIdFromProject(form.project.data, form.name.data)
            flash(f'{"Element Registered "}', 'success')
            return redirect(url_for('project.show_element', elementId=element.id))

        return render_template('register_form.html',
                                title="Register Element",
                                theme=themeMinibase,
                                globalVars=globalVars,
                                form=form)
    else:
        flash(f'{"TO register a project element you need to select a company first"}', 'warning')
        return redirect(url_for('company.select_company'))
