import os
import re
import typing as t

from lxml import etree
from flask import Blueprint, abort, render_template, request, send_from_directory
from peewee import *

from .app import APPPATH
from .modeles import Institution, State, House, Intervention_type, Production_place, Diplo_type, Document, Acte, Individual, Involved_in

RESULT_PAR_PAGES = 5

main = Blueprint("main", __name__, url_prefix="/")


@main.route("/")
def home():
    """home route"""
    return render_template("home.html")

@main.route("/about/")
def about():
    """home route"""
    return render_template("about.html")

@main.route("/actes/")
def corpora_all():
    """copora all route"""
    return render_template("corpora_all.html")

@main.route("/actes/<house>")  # dont put a slash at the end
def actes(house):
    """actes route"""
    house_q = [t.id_house for t in House.select().where(
                    House.house_label == house)]
    prince_q = [(t.name_indiv, t.id_indiv) for t in Individual.select().where(
                    (Individual.role_indiv == "prince")
                    &(Individual.house_indiv == house_q[0]))]
    return render_template("corpus.html", house=house, princes=prince_q)

@main.route("/actes/<house>/<prince>")  # don't put a slash at the end
def prince_corpus(house=None, prince=None):
    """copora prince route"""
    prince_name = [[t.name_indiv, t.id_indiv] for t in Individual.select().where(
                    Individual.id_indiv == prince)]
    actes=[t.involved_in_acte for t in Involved_in.select().where(
                    (Involved_in.involved_in_prince == prince)
                    &(Involved_in.invol_in_interv == 1))]
    prince_acte = []
    for acte in actes:
        info = [(t.date, t.filename, t.analysis, t.prod_place_acte,
                t.diplo_type_acte, t.state_doc) for t in Acte.select(
                    ).where(Acte.id_acte == acte)]
        place = [t.placename for t in Production_place.select().where(
            Production_place.id_place == info[0][3])]
        diplo_t = [t.diplo_label for t in Diplo_type.select().where(
            Diplo_type.id_diplo_type == info[0][4])]
        state = [t.state_label for t in State.select().where(
            State.id_state == info[0][5])]
        # avoid TypeError: 'tuple' object does not support item assignment :
        infos_lst = list(info[0])
        infos_lst[3] = place[0]
        infos_lst[4] = diplo_t[0].replace("_", " ")
        infos_lst[5] = state[0]
        prince_acte.append(infos_lst)

    prince_acte = sorted(prince_acte)
    # print(prince_acte)
    
    return render_template("prince_corpus.html", houseS=house, duke_name=prince_name,
            lst_id=prince_acte)

@main.route("/acte/<prince>/<acte_id>")  # don't put a slash at the end
def acte(house=None, prince=None, acte_id=None):
    """acte route"""
    q_prod = Involved_in.select().where(
                    (Involved_in.involved_in_prince == prince)
                    &(Involved_in.invol_in_interv == 1))
    q_acte = Acte.select().where(
        Acte.filename == acte_id)
    for t in q_acte:
        acte_place_id = t.prod_place_acte
        acte_doc = t.doc_acte
        acte_state_id = t.state_doc
        acte_diplo_type = t.diplo_type_acte
    place = [t.placename for t in Production_place.select().where(
            Production_place.id_place == acte_place_id)]
    diplo_t = [t.diplo_label for t in Diplo_type.select().where(
            Diplo_type.id_diplo_type == acte_diplo_type)]
    state = [t.state_label for t in State.select().where(
            State.id_state == acte_state_id)]
    doc = [[t.collection_doc, t.inst_doc] for t in Document.select().where(
            Document.id_document == acte_doc)]
    inst = [t.full_label for t in Institution.select().where(
            Institution.id_institution == doc[0][1])]
    prince_name = [t.name_indiv for t in Individual.select().where(
            Individual.id_indiv == prince)]

    # if the acte if in another house's folder,
    # change <house> according to the begining of filename
    # (i. e. the house abreviation)
    dict_house = {'brb': 'Bourbon', 'bry': 'Berry', 'anj': 'Anjou'}
    pattern_house = re.compile(r'([a-z]{3})_[a-z]+_[ivx]+_\d+(_\d+)?(_\d+)?[a-z]')
    name_house = re.search(pattern_house, acte_id)
    house = dict_house[name_house.group(1)]

    source_doc = etree.parse(
        os.path.join(APPPATH, "static", "xml", house, acte_id + '.xml'))
    # remove namespace :
    query = "descendant-or-self::*[namespace-uri()!='']"
    for element in source_doc.xpath(query):
        #replace element name with its local name
        element.tag = etree.QName(element).localname
    etree.cleanup_namespaces(source_doc)

    xslt_doc = etree.parse(os.path.join(APPPATH, "static", "xsl", "actes_princiers.xsl"))
    xslt_transformer = etree.XSLT(xslt_doc)
    output_doc = xslt_transformer(source_doc)
    return render_template("acte.html", house=house, prince=prince,
        infos=q_acte, place=place[0], doc=doc[0][0], arch=inst[0],
        diplo=diplo_t[0].replace("_", " "), state=state[0],
        output_doc=output_doc, name_prince=prince_name[0])

@main.route("/contact")
def contact() -> t.Text:
    """Displays the Contact page"""
    return render_template("contact.html", title="Contact")

@main.route("/termsofservice")
def terms() -> t.Text:
    """Displaysthe T&C page."""
    return render_template("terms.html", title="Mentions légales")

@main.route("/privacy")
def privacy() -> t.Text:
    """Displays the privacy policy page."""
    return render_template("privacy.html", title="Politique de confidentialité")
