# -*- 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 os
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QDialog, QMessageBox
# from qgis.PyQt.QtGui import QIcon

# from qgis.PyQt.QtCore import *
# from qgis.PyQt.QtGui import *
from qgis.PyQt import QtGui

# from qgis.core import *
from qgis.core import QgsSettings, Qgis

try:
    if os.path.exists('N:'):
        from .tools.PythonSQL import login_base
except ValueError:
    print('Pas de fichier PythonSQL')

# from .tools.SQLRequet import *

from .tools.resources import (
    load_ui,
    resources_path,
    # send_issues,
    create_vierge,
    create_contour,
    create_travaux,
    create_habita
)
# 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):
        self.activateWindow()
        # 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():
                # Ajout de "_" pour eviter pb de numero en premier caractere
                schema = "_" + self.dept.currentText() + "_at_" + self.nom.text().lower()
            else:
                # Ajout de "_" pour eviter pb de numero en premier caractere
                schema = "_" + self.dept.currentText() + "_" + self.nom.text().lower()

            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
            account = login_base("account")
            user = account[0]
            mdp = account[1]
            host = account[2]
            port = account[3]
            dbname = account[4]
            cur = account[7]
            con = account[8]

            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;"

            if self.couche_contour.isChecked() or self.couche_habitat.isChecked() or self.couche_travaux_prevus.isChecked() or self.couche_vierge.isChecked():
                cur.execute(SQL_schema)
                cur.execute(SQL_GRANT_SCHEMA)
            else:
                iface.messageBar().pushMessage("POSTGRESQL :", "Pas de couche sélectionnée, création refusée.", level=Qgis.Warning, duration=30)

            create_contour(self, schema, cur, con, host, port, dbname, user, mdp)
            create_habita(self, schema, cur, con, host, port, dbname, user, mdp)
            create_travaux(self, schema, cur, con, host, port, dbname, user, mdp)
            create_vierge(self, schema, cur, con, host, port, dbname, user, mdp)

            con.close()
            pass
