__copyright__ = "Copyright 2021, 3Liz"
__license__ = "GPL version 3"
__email__ = "info@3liz.org"


from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface
import qgis


# include <QSettings>

import socket
import os
from qgis.PyQt.QtCore import QSettings
from .about_form import AboutDialog
from .tools.resources import (
    # plugin_path,
    pyperclip,
    resources_path,
    maj_verif,
)
pyperclip()

try:
    from .postgis_editor import Postgis_Editor
    from .postgis_creator import Postgis_Creator
    from .postgis_rename import Postgis_Rename
except NameError:
    print('Module introuvable...')

IPAddr = socket.gethostbyname(socket.gethostname())


class PgPostgis:
    def __init__(self):
        """ Constructor. """
        self.action_editor = None
        self.action_creator = None
        self.action_rename = None
#        self.issues = None
        self.provider = None
        self.locator_filter = None
        self.dock_action = None
        self.help_action = None
        plugin_dir = os.path.dirname(__file__)
        end_find = plugin_dir.rfind('\\') + 1
        global NAME
        NAME = plugin_dir[end_find:]
        maj_verif(NAME)

        # Display About window on first use
        version = qgis.utils.pluginMetadata('CenRa_POSTGIS', 'version')
        s = QSettings()
        versionUse = s.value("postgis/version", 1, type=str)
        if str(versionUse) != str(version):
            s.setValue("postgis/version", str(version))
            print(versionUse, version)
            self.open_about_dialog()

    def initGui(self):
        """ Build the plugin GUI. """

        self.toolBar = iface.addToolBar("CenRa_Postgis")
        self.toolBar.setObjectName("CenRa_Postgis")

        icon = QIcon(resources_path('icons', 'page_new.png'))
        icon2 = QIcon(resources_path('icons', 'page_ajout.png'))
        icon3 = QIcon(resources_path('icons', 'page_rename.png'))

        # Open the online help
        self.help_action = QAction(icon, "CenRa_Postgis", iface.mainWindow())
        iface.pluginHelpMenu().addAction(self.help_action)
        self.help_action.triggered.connect(self.open_help)
        if not self.action_creator:
            self.action_creator = Postgis_Creator()

            self.postgis_creator = QAction(icon, 'dossier_creator', None)
            self.toolBar.addAction(self.postgis_creator)
            self.postgis_creator.triggered.connect(self.open_creator)

            self.postgis_creator.setEnabled(False)
            if os.access('N:/', os.R_OK):
                self.postgis_creator.setEnabled(True)

        if not self.action_editor:
            self.action_editor = Postgis_Editor()

            self.postgis_editor = QAction(icon2, 'dossier_editor', None)
            self.toolBar.addAction(self.postgis_editor)
            self.postgis_editor.triggered.connect(self.open_editor)

            self.postgis_editor.setEnabled(False)
            if os.access('N:/', os.R_OK):
                self.postgis_editor.setEnabled(True)

        if not self.action_rename:
            self.action_rename = Postgis_Rename()

            self.postgis_rename = QAction(icon3, 'dossier_rename', None)
            self.toolBar.addAction(self.postgis_rename)
            self.postgis_rename.triggered.connect(self.open_rename)
            self.postgis_rename.setEnabled(False)
            self.postgis_rename.setVisible(0)

            if os.environ['USERNAME'] == 'tlaveille' or os.environ['USERNAME'] == 'lpoulin' or os.environ['USERNAME'] == 'rclement':
                if os.access('N:/', os.R_OK):
                    self.postgis_rename.setEnabled(True)
                self.postgis_rename.setVisible(1)

    def open_about_dialog(self):
        """
        About dialog
        """
        dialog = AboutDialog(iface)
        dialog.exec()

    def open_help():
        """ Open the online help. """
        QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))

    def open_editor(self):
        self.action_editor.show()
        self.action_editor.raise_()

    def open_creator(self):
        self.action_creator.show()
        self.action_creator.raise_()

    def open_rename(self):
        self.action_rename.show()
        self.action_rename.raise_()

    def unload(self):
        """ Unload the plugin. """
        if self.action_editor:
            iface.removePluginMenu('CenRa_Postgis', self.postgis_editor)
        if self.action_creator:
            iface.removePluginMenu('CenRa_Postgis', self.postgis_creator)
        if self.action_rename:
            iface.removePluginMenu('CenRa_Postgis', self.postgis_rename)

        if self.provider:
            QgsApplication.processingRegistry().removeProvider(self.provider)
            del self.provider

        if self.locator_filter:
            iface.deregisterLocatorFilter(self.locator_filter)
            del self.locator_filter

        if self.help_action:
            iface.pluginHelpMenu().removeAction(self.help_action)
            del self.help_action
