# -*- 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, QDialogButtonBox
# 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, QgsDataSourceUri, QgsProject

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,
)
# from .issues import CenRa_Issues

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

EDITOR_CLASS = load_ui('CenRa_PostgisRename_base.ui')
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" "]
try:
    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]
except NameError:
    print('Fails to login DB for account')


class Postgis_Rename(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

        self.schema.currentIndexChanged.connect(self.Test)
        self.buttonBox.accepted.connect(self.msgBox)
    # Outil Ajout de nouvelles couche a un dossier

    def raise_(self):
        self.activateWindow()
        self.groupBox_3.hide()
        self.buttonBox.button(QDialogButtonBox.StandardButton(0x00000400)).setEnabled(False)
        GET_ALL_SCHEMA = """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema LIKE '_form_%' OR table_schema LIKE '_01_%' OR table_schema LIKE '_07_%' OR table_schema LIKE '_26_%' OR table_schema LIKE '_42_%' OR table_schema LIKE '_69_%' ORDER BY table_schema;"""
        cur.execute(GET_ALL_SCHEMA)
        AllSchema = cur.fetchall()
        last_value_schema = self.schema.currentText()
        last_value_departement = self.departement.currentText()
        self.schema.clear()
        self.departement.clear()
        self.schema.addItems([''])
        for Schema in AllSchema:
            self.schema.addItems(Schema)
        self.departement.addItems(['', '01', '07', '26', '42', '69', 'form'])
        if last_value_schema != '':
            self.schema.setCurrentIndex(self.schema.findText(last_value_schema))
        if last_value_departement != '':
            self.departement.setCurrentIndex(self.departement.findText(last_value_departement))

    def Test(self):
        oldSchema = self.schema.currentText()
        if oldSchema != '':
            allIsGood = 0

            GET_COUNT_LEFT = "SELECT count(*) FROM information_schema.tables WHERE table_schema LIKE left(table_name," + str(len(oldSchema)) + ") AND table_schema LIKE '" + oldSchema + "';"
            GET_COUNT_TOT = "SELECT count(*) FROM information_schema.tables WHERE table_schema LIKE '" + oldSchema + "';"

            cur.execute(GET_COUNT_TOT)
            CountTot = cur.fetchall()[0]
            cur.execute(GET_COUNT_LEFT)
            CountLeft = cur.fetchall()[0]

            if CountLeft[0] == CountTot[0]:
                allIsGood = allIsGood + 1
                self.couche.setChecked(1)
            else:
                self.couche.setChecked(0)

            GET_GRANTEE_PRIVILEGE = "SELECT DISTINCT count(*) FROM information_schema.role_table_grants WHERE table_schema LIKE '" + oldSchema + "' AND grantee LIKE 'grp_qgis' AND privilege_type LIKE 'UPDATE';"
            cur.execute(GET_GRANTEE_PRIVILEGE)
            CountPrivilege = cur.fetchall()[0]

            if CountTot[0] == CountPrivilege[0]:
                allIsGood = allIsGood + 1
                self.compte.setChecked(1)
            else:
                self.compte.setChecked(0)

            if allIsGood == 2:
                self.groupBox_3.show()
                self.loadValue()
                self.buttonBox.button(QDialogButtonBox.StandardButton(0x00000400)).setEnabled(True)
            else:
                self.groupBox_3.hide()
                self.buttonBox.button(QDialogButtonBox.StandardButton(0x00000400)).setEnabled(False)
        else:
            self.old_name.setText('')
            self.compte.setChecked(0)
            self.couche.setChecked(0)
            self.groupBox_3.hide()

    def loadValue(self):
        oldSchema = self.schema.currentText()
        if oldSchema[:6] == '_form_':
            oldSchema = self.schema.currentText()[6:]
            prefixSchema = self.schema.currentText()[1:5]
        else:
            oldSchema = self.schema.currentText()[4:]
            prefixSchema = self.schema.currentText()[1:3]
        if oldSchema[:3] == 'at_':
            oldSchema = oldSchema[3:]
            self.animation.setChecked(1)
        else:
            self.animation.setChecked(0)
        self.old_name.setText(oldSchema)
        self.departement.setCurrentIndex(self.departement.findText(prefixSchema))

    def updateName(self):
        if self.departement.currentText() != '':
            oldTableName = self.old_name.text()
            newTableName = ((self.new_name.text()).lower()).replace(' ', '_')
            newPrefixSchema = '_' + self.departement.currentText() + '_'
            if self.schema.currentText()[:6] == '_form_':
                oldPrefixSchema = self.schema.currentText()[:6]
                if (self.schema.currentText()[6:9]) == "at_":
                    oldPrefixSchema = oldPrefixSchema + 'at_'
            else:
                oldPrefixSchema = self.schema.currentText()[:4]
                if (self.schema.currentText()[4:7]) == 'at_':
                    oldPrefixSchema = oldPrefixSchema + 'at_'

            if self.animation.isChecked():
                newPrefixSchema = newPrefixSchema + 'at_'
            oldSchemaName = oldPrefixSchema + oldTableName
            newSchemaName = newPrefixSchema + newTableName

            if oldSchemaName != newSchemaName:
                global AllSQLrun
                allSQLrun = ''

                SQL_UPDATE = """UPDATE public.layer_styles SET f_table_schema = '""" + newSchemaName + """',f_table_name = replace(replace(f_table_name,'""" + oldTableName + """','""" + newTableName + """'),'""" + oldPrefixSchema + """','""" + newPrefixSchema + """') WHERE f_table_schema LIKE '""" + oldSchemaName + """';"""
                allSQLrun = allSQLrun + SQL_UPDATE
                cur.execute(SQL_UPDATE)

                SQL_GET_TABLE_RENAME = """SELECT table_name,replace(replace(table_name,'""" + oldTableName + """','""" + newTableName + """'),'""" + oldPrefixSchema + """','""" + newPrefixSchema + """') from information_schema.tables WHERE table_schema LIKE '""" + oldSchemaName + """';"""
                cur.execute(SQL_GET_TABLE_RENAME)
                allTableRename = cur.fetchall()
                allTableList = []
                for TableRename in allTableRename:
                    oldTable = TableRename[0]
                    newTable = TableRename[1]
                    allTableList.append([oldTable, newSchemaName, newTable])
                    SQL_RENAME_TABLE = """ALTER TABLE """ + oldSchemaName + '.' + oldTable + """ RENAME TO """ + newTable + """;"""
                    allSQLrun = allSQLrun + SQL_RENAME_TABLE
                    cur.execute(SQL_RENAME_TABLE)

                SQL_RENAME_SCHEMA = 'ALTER SCHEMA ' + oldSchemaName + ' RENAME TO ' + newSchemaName
                allSQLrun = allSQLrun + SQL_RENAME_SCHEMA
                cur.execute(SQL_RENAME_SCHEMA)
                con.commit()
                for LayerOpen in allTableList:
                    self.UnloadLoadLayers(LayerOpen[0], LayerOpen[1], LayerOpen[2])

    def UnloadLoadLayers(self, OldName, NewSchema, NewTable):
        allLayers = (QgsProject.instance().mapLayers().values())
        listLayers = []
        listLayersName = []
        for layer in allLayers:
            listLayers.append(layer)
            listLayersName.append(layer.name())
        if OldName in listLayersName:
            layer = (listLayers[listLayersName.index(OldName)])
            provider = layer.dataProvider()
            dbname = (QgsDataSourceUri(provider.dataSourceUri()).database())
            user = QgsDataSourceUri(provider.dataSourceUri()).username()
            mdp = QgsDataSourceUri(provider.dataSourceUri()).password()
            host = QgsDataSourceUri(provider.dataSourceUri()).host()
            port = QgsDataSourceUri(provider.dataSourceUri()).port()

            # 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(NewSchema, NewTable, 'geom')
            QgsProject.instance().removeMapLayer(layer.id())
            layer = self.iface.addVectorLayer(uri.uri(), NewTable, "postgres")

    def msgBox(self):
        self.QMBquestion = QMessageBox()
        self.QMBquestion.setWindowTitle(u"Attention !")
        self.QMBquestion.setIcon(QMessageBox.Icon.Warning)
        self.QMBquestion.setText("Attention, le renommage de dossier PostGIS peut engendrer des pertes de liaisons avec des projets QGIS !")
        self.QMBquestion.setStandardButtons(QMessageBox.StandardButton(0x00004000) | QMessageBox.StandardButton(0x00010000))
        if self.new_name.text() != '':
            error_caracteres = 0
            for caracteres in ch:
                if self.new_name.text().find(caracteres) != - 1:
                    error_caracteres = 1
            if error_caracteres == 0:
                self.QMBquestion = self.QMBquestion.exec()
            else:
                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.new_name.text().lower())
        else:
            QMessageBox.warning(None, "Oups :", "Votre projet doit avoire un nom !")
        if self.QMBquestion == QMessageBox.StandardButton(0x00004000):
            self.updateName()
