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

from __future__ import absolute_import
# Import the PyQt and QGIS libraries
from builtins import next
from builtins import str
import os

from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QDialog, QMessageBox
# from qgis.PyQt.QtGui import QIcon

from qgis.PyQt import QtGui

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

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

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

EDITOR_CLASS = load_ui('CenRa_PostgisTable_base.ui')


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

    # Outil Ajout de nouvelles couche a un dossier
    def raise_(self):
        self.activateWindow()
        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]
        # Creation de la liste des schemas de la base de donnees
        SQL = """WITH list_schema AS (
    select schemaname,'sig' as group from pg_catalog.pg_tables
    where schemaname  ~ E'^_(0|1|2|3|4|6|7|f)'
    group by schemaname
    order by schemaname)
    select  string_agg(schemaname,',')
    from list_schema
    group by "group";"""

        cur.execute(SQL)

        list_brut = str(next(cur))
        list = list_brut[2:-2]
        listItems = list.split(",")

        con.close()

        self.schema.clear()
        self.schema.addItems(listItems)
        # Pour ne pas commencer la liste au premier schema
        self.schema.setCurrentIndex(-1)

        # show the dialog
        self.show()
        # Run the dialog event loop
        result = self.exec()
        # See if OK was pressed
        if result == 1:
            # ******************************debut script*********************************
            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]

            if self.schema.currentIndex() == - 1:
                QMessageBox.warning(None, "Oups :", "Veuillez choisir un nom de dossier.")
                return

            schema = self.schema.currentText()

            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
