# -*- coding: utf-8 -*-

from __future__ import absolute_import
# Import the PyQt and QGIS libraries
from builtins import next
from builtins import str
from builtins import object
import qgis
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog
from qgis.PyQt.QtGui import QIcon
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtGui
from qgis.core import *
from qgis.core import QgsDataSourceUri

from .tools.PythonSQL import *
from .tools.resources import (
    load_ui,
    resources_path,
    login_base,
    send_issues,
)
from .issues import CenRa_Issues

from qgis.utils import iface
import os.path
import webbrowser, os
import psycopg2
import psycopg2.extras
import base64

EDITOR_CLASS = load_ui('CenRa_Postgis_base.ui')

class Postgis_Creator(QDialog, EDITOR_CLASS):

    def __init__(self, parent=None):
        _ = parent
        super().__init__()
        self.setupUi(self)
        self.settings = QgsSettings()
        self.s = QSettings()
        self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
        self.iface = iface

    # run method that performs all the real work
    def raise_(self):
        # show the dialog
        self.show()
        # Run the dialog event loop
        result = self.exec_()
        # See if OK was pressed
        if result == 1:

#**********************************Debut_script****************************************

            ### Creation du schema pour le nouveau site
            if self.at.isChecked():
                schema = "_" + self.dept.currentText() + "_at_" + self.nom.text().lower() # Ajout de "_" pour eviter pb de numero en premier caractere
            else :
                schema = "_" + self.dept.currentText() + "_" + self.nom.text().lower() # Ajout de "_" pour eviter pb de numero en premier caractere

            if self.nom.text() == "" or self.nom.text() == "NULL":
                QMessageBox.warning(None, "Oups :", "Veuillez renseigner un nom de dossier.")
                return

            ch = [u"à", u"À", u"â", u"Â", u"ä", u"Ä", u"å", u"Å", u"ç", u"Ç", u"é", u"É", u"è", u"È", u"ê", u"Ê", u"ë", u"Ë", u"î", u"Î", u"ï", u"Ï", u"ô", u"Ô", u"ö", u"Ö", u"ù", u"Ù", u"û", u"Û", u"ü", u"Ü", u"ÿ", u"Ÿ", u"'", u"-", u" "]
            for car in ch :
                if self.nom.text().find(car) != -1 :
                    QMessageBox.warning(None, "Oups :", u"Le nom de dossier ne doit pas comporter de caractères spéciaux, ni d'espaces !\n\n\t" + self.nom.text().lower() )
                    return
            first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=first_cnx password=" + password)
            first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
            first_cur.execute("SELECT mdp_w, login_w FROM pg_catalog.pg_user t1, admin_sig.vm_users_sig t2 WHERE t2.oid = t1.usesysid AND (login_w = '" + os_user + "' OR login_w = '" + os_user + "')")
            res_ident = first_cur.fetchone()
            mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
            user = res_ident[1]
            con = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=" + user + " password=" + mdp)
            cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor)
            first_conn.close()

            SQL_schema = "CREATE SCHEMA " + schema + ";"
            SQL_GRANT_SCHEMA="GRANT CREATE, USAGE ON SCHEMA "+schema+" TO grp_qgis; GRANT CREATE, USAGE ON SCHEMA "+schema+" TO grp_sig;"

            cur.execute(SQL_schema)
            cur.execute(SQL_GRANT_SCHEMA)

            ### Creation de la table contour
            if self.couche_contour.isChecked(): # Verifie si la checkbox est cochee
                if     self.annee_1.text() == 'aaaa' or self.annee_1.text() == '':
                    tablename = schema + "_contour"
                else :
                    tablename = schema + "_contour_" + self.annee_1.text()
                tablename_qgis = tablename[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis

                SQL_contour = "CREATE TABLE " + schema + "."+ tablename + champ_contour
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
                SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
                SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
                SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"

                SQL_style = """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'contour_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_contour)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_area_m2)
                cur.execute(SQL_trigger_area_ha)
                cur.execute(SQL_trigger_date_creation)
                cur.execute(SQL_trigger_date_maj)
                cur.execute(SQL_style)    ## Enregistrement du style (comme style par defaut) dans la table layer_styles
                cur.execute(SQL_GRANT_TABLE)

                con.commit()

                ## Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

            ### Creation de la table habitat
            if self.couche_habitat.isChecked():
                if     self.annee_2.text() == 'aaaa' or self.annee_2.text() == '':
                    tablename = schema + "_habitat"
                else :
                    tablename = schema + "_habitat_" + self.annee_2.text()
                tablename_1=tablename+"_points"
                tablename_qgis = tablename_1[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis
                SQL_VEGETHAB = "CREATE TABLE "+ schema + "."+ tablename_1 + champ_vegethab_point
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename_1 + " ADD CONSTRAINT " + tablename_1 + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_coordonnees = "CREATE TRIGGER coordonnees" + tablename_1 + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename_1 + " FOR EACH ROW EXECUTE PROCEDURE ref.coordonnees();"
                SQL_style = """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename_1 + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'vegethab_points_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_1+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_1+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename_1+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_VEGETHAB)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_coordonnees)
                cur.execute(SQL_style)
                cur.execute(SQL_GRANT_TABLE)

                con.commit()
                ### Affichage de la table
                uri = QgsDataSourceUri()
                # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename_1, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

                tablename_2=tablename+"_lignes"
                tablename_qgis = tablename_2[1:]
                SQL_VEGETHAB = "CREATE TABLE "+ schema + "."+ tablename_2 + champ_vegethab_multilinestring
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename_2 + " ADD CONSTRAINT " + tablename_2 + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_length_m = "CREATE TRIGGER length_m" + tablename_2 + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename_2 + " FOR EACH ROW EXECUTE PROCEDURE ref.length_m();"
                SQL_trigger_length_km = "CREATE TRIGGER length_km" + tablename_2 + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename_2 + " FOR EACH ROW EXECUTE PROCEDURE ref.length_km();"
                SQL_style = """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename_2 + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'vegethab_lignes_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_2+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_2+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename_2+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_VEGETHAB)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_length_m)
                cur.execute(SQL_trigger_length_km)
                cur.execute(SQL_style)
                cur.execute(SQL_GRANT_TABLE)

                con.commit()
                ### Affichage de la table
                uri = QgsDataSourceUri()
                # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename_2, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

                tablename_3=tablename+"_polygones"
                tablename_qgis = tablename_3[1:]
                SQL_VEGETHAB = "CREATE TABLE "+ schema + "."+ tablename_3 + champ_vegethab_multipolygon
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename_3 + " ADD CONSTRAINT " + tablename_3 + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename_3 + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename_3 + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
                SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename_3 + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename_3 + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
                SQL_style = """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename_3 + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'vegethab_polygones_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_3+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename_3+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename_3+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_VEGETHAB)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_area_m2)
                cur.execute(SQL_trigger_area_ha)
                cur.execute(SQL_style)
                cur.execute(SQL_GRANT_TABLE)

                con.commit()
                ### Affichage de la table
                uri = QgsDataSourceUri()
                # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename_3, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
                '''
                SQL_habitat = "CREATE TABLE " + schema + "."+ tablename + champ_habitat
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
                SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
                SQL_trigger_concat_cd_cb = "CREATE TRIGGER concat_cd_cb" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.concat_cd_cb();"
                SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
                SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"

                SQL_style =    """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'habitat_modele_v3'"""

                cur.execute(SQL_habitat)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_area_m2)
                cur.execute(SQL_trigger_area_ha)
                cur.execute(SQL_trigger_concat_cd_cb)
                cur.execute(SQL_trigger_date_creation)
                cur.execute(SQL_trigger_date_maj)
                cur.execute(SQL_style)    ## Enregistrement du style (comme style par defaut) dans la table layer_styles

                con.commit()

                ## Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
                '''
            ### Creation de la table travaux prevus
            if self.couche_travaux_prevus.isChecked():
                    #**********Poly
                if     self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
                    tablename = schema + "_travaux_prevus_poly"
                else :
                    tablename = schema + "_travaux_prevus_poly_" + self.annee_5.text()
                tablename_qgis = tablename[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis

                SQL_travaux_prevus = "CREATE TABLE " + schema + "."+ tablename + champ_travaux_prevus_multipolygon
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
                SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"
                SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
                SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"

                SQL_style =    """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'travaux_prevus_poly_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_travaux_prevus)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_date_creation)
                cur.execute(SQL_trigger_date_maj)
                cur.execute(SQL_trigger_area_m2)
                cur.execute(SQL_trigger_area_ha)
                cur.execute(SQL_style)    ## Enregistrement du style (comme style par defaut) dans la table layer_styles
                cur.execute(SQL_GRANT_TABLE)


                con.commit()

                ## Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

                    #**********ligne
                if     self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
                    tablename = schema + "_travaux_prevus_ligne"
                else :
                    tablename = schema + "_travaux_prevus_ligne_" + self.annee_5.text()
                tablename_qgis = tablename[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis

                SQL_travaux_prevus = "CREATE TABLE " + schema + "."+ tablename + champ_travaux_prevus_multilinestring
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
                SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"
                SQL_trigger_length_m = "CREATE TRIGGER length_m" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_m();"
                SQL_trigger_length_km = "CREATE TRIGGER length_km" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_km();"

                SQL_style =    """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'travaux_prevus_ligne_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_travaux_prevus)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_date_creation)
                cur.execute(SQL_trigger_date_maj)
                cur.execute(SQL_trigger_length_m)
                cur.execute(SQL_trigger_length_km)
                cur.execute(SQL_style)    ## Enregistrement du style (comme style par defaut) dans la table layer_styles
                cur.execute(SQL_GRANT_TABLE)


                con.commit()

                ## Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

                    #**********point
                if     self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
                    tablename = schema + "_travaux_prevus_point"
                else :
                    tablename = schema + "_travaux_prevus_point_" + self.annee_5.text()
                tablename_qgis = tablename[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis

                SQL_travaux_prevus = "CREATE TABLE " + schema + "."+ tablename + champ_travaux_prevus_point
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
                SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
                SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"
                SQL_trigger_coordonnees = "CREATE TRIGGER coordonnees" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.coordonnees();"

                SQL_style =    """INSERT INTO layer_styles (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, update_time)
                SELECT f_table_catalog, '""" + schema + "', '" + tablename + """', f_geometry_column, stylename, styleqml, stylesld, useasdefault, "owner", ui, now()
                FROM layer_styles
                WHERE description = 'travaux_prevus_point_modele_v3'"""
                SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_sig;GRANT ALL ON SEQUENCE "+schema+"."+tablename+"_gid_seq TO grp_qgis;"

                cur.execute(SQL_travaux_prevus)
                cur.execute(SQL_pkey)
                cur.execute(SQL_trigger_date_creation)
                cur.execute(SQL_trigger_date_maj)
                cur.execute(SQL_trigger_coordonnees)
                cur.execute(SQL_style)    ## Enregistrement du style (comme style par defaut) dans la table layer_styles
                cur.execute(SQL_GRANT_TABLE)


                con.commit()

                ## Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

            ### Creation de la table vierge
            if self.couche_vierge.isChecked():
                if     self.annee_4.text() == 'aaaa' or self.annee_4.text() == '':
                    tablename = schema + "_" + self.nom_couche_vierge.text().lower()
                else :
                    tablename = schema + "_" + self.nom_couche_vierge.text().lower() + "_" + self.annee_4.text()
                tablename_qgis = tablename[1:]  # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis

                if self.couche_vierge_point.isChecked() == 1 :
                    champ_vierge = champ_viergePoint

                if self.couche_vierge_ligne.isChecked() == 1 :
                    champ_vierge = champ_viergeLigne

                if self.couche_vierge_polygone.isChecked() == 1 :
                    champ_vierge = champ_viergePolygone

                SQL_vierge = "CREATE TABLE " + schema + "."+ tablename + champ_vierge
                SQL_pkey =  "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"

                SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
                SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
                SQL_trigger_length_m = "CREATE TRIGGER length_m" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_m();"
                SQL_trigger_length_km = "CREATE TRIGGER length_km" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_km();"
                SQL_trigger_coordonnees = "CREATE TRIGGER coordonnees" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.coordonnees();"

                cur.execute(SQL_vierge)
                cur.execute(SQL_pkey)

                if self.couche_vierge_point.isChecked() == 1 :
                    cur.execute(SQL_trigger_coordonnees)

                if self.couche_vierge_ligne.isChecked() == 1 :
                    cur.execute(SQL_trigger_length_m)
                    cur.execute(SQL_trigger_length_km)

                if self.couche_vierge_polygone.isChecked() == 1 :
                    cur.execute(SQL_trigger_area_m2)
                    cur.execute(SQL_trigger_area_ha)

                con.commit()

                ### Affichage de la table
                uri = QgsDataSourceUri()
                  # set host name, port, database name, username and password
                uri.setConnection(host ,port ,dbname ,user ,mdp)
                  # set database schema, table name, geometry column and optionaly subset (WHERE clause)
                uri.setDataSource(schema, tablename, geom)

                layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")

            else :
                con.commit()

            con.close()
            pass