# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ArheoloskiGis
                                 A QGIS plugin
 This plugin loads useful layers
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-02-22
        git sha              : $Format:%H$
        copyright            : (C) 2020 by Matjaž Mori, ZVKDS CPA
        email                : matjaz.mori@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon, QPixmap
from qgis.PyQt.QtWidgets import (QAction,
                                QMenu,
                                QDialogButtonBox,
                                QCheckBox)
from qgis.core import (QgsProject,
                       QgsRasterLayer,
                       QgsVectorLayer,
                       QgsLayerDefinition,
                       QgsCoordinateReferenceSystem,
                       QgsLayerTreeLayer

                       )
import tempfile
import shutil


# Initialize Qt resources from file resources.py
from ..resources import *
# Import the code for the dialog
from .agis_load_dialog import ArheoloskiGisLoadDialog
import os.path
from pathlib import Path
from ..externals import (path,
                        access,
                        postgis_connect
                        )
import tempfile
import shutil

class ArheoloskiGisLoad:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ArheoloskiGis_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.dlg = ArheoloskiGisLoadDialog()


        self.dlg.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(self.dlg.close)
        self.dlg.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.load_layers)
        self.dlg.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.dlg.close)


        logo_path = path('icons')/"loader_logo_small"
        self.dlg.label_2.setPixmap(QPixmap(str(logo_path)))
        # Declare instance attributes
        self.actions = []
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('ArheoloskiGis', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this='aaa',
        parent=None):

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/agis/icons/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'AGIS'),
            callback=self.run,
            parent=self.iface.mainWindow())
        # will be set False in run()

        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&AGIS'),
                action)
            self.iface.removeToolBarIcon(action)


    def run(self):
        """Run method that performs all the real work"""
        if self.first_start == True:
            self.first_start = False
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass


   
    def load_layers(self):
        root = QgsProject.instance().layerTreeRoot()
        crs = QgsCoordinateReferenceSystem("EPSG:3794")

        #To prevent folder locking of Plugin directory
        try:
            tmp = tempfile.mkdtemp()
            src = path('qlrs')
            shutil.rmtree(tmp)
            shutil.copytree(str(src), tmp)
            styles_path = Path(tmp)
        except:
            self.iface.messageBar().pushMessage(self.tr('Reading from plugin dir'))

        #Clean layers (On update use:  names = [layer.name() for layer in QgsProject.instance().mapLayers().values()] ; print (names)  )
        if self.dlg.prostorske_enote.isChecked():
            layers = ['AO_topo75_1880', 'eVRD', 'RKD', 'AO_topo75_1914', 'Claustra Alpium Iuliarum', 'DTK50_1950_1967', 'Evidenca arheoloških raziskav', 'Katalog najdišč', 'ZLS SVF', 'Načrti najdišč', 'Načrti najdišč_poligoni', 'Parcele', 'DTK5', 'Državna meja Republike Slovenije', 'Naselja', 'Občine', 'Katastrske občine', 'DOF050', 'SMAP', 'ZLS 1m', 'ZLS interpretacija', 'Franciscejski kataster', 'DPK1000', 'DPK250', 'DPK500', 'DTK50']
            try:
                for layer in layers:
                    for b in QgsProject.instance().mapLayersByName(layer): 
                        lay = b.id()
                        QgsProject.instance().removeMapLayer(str(lay))
            except:
                pass
        else:
            pass

        #Load Arheologija layes group

        if not root.findGroup("Arheologija"):
            arheo_group = root.addGroup("Arheologija")
        else:
            arheo_group = root.findGroup("Arheologija")

        if access(self):
            vlayer = postgis_connect(self, "public", "Katalog najdišč", "geom", "kid")
            QgsProject.instance().addMapLayer(vlayer, False)  
            arheo_group.insertChildNode(0, QgsLayerTreeLayer(vlayer))

            vlayer = postgis_connect(self, "public", "Evidenca arheoloških raziskav", "geom", "id")
            QgsProject.instance().addMapLayer(vlayer, False)   
            arheo_group.insertChildNode(1, QgsLayerTreeLayer(vlayer)) 

            arch_layers = ['Claustra Alpium Iuliarum', 'Načrti najdišč', 'Načrti najdišč_poligoni']
            for layer in arch_layers:
                vlayer = postgis_connect(self, "public", layer, "geom", "id")
                QgsProject.instance().addMapLayer(vlayer, False)   
                arheo_group.insertChildNode(2, QgsLayerTreeLayer(vlayer)) 
            
            arch_layers = ['SMAP', 'ZLS interpretacija']
            for layer in arch_layers:
                vlayer = postgis_connect(self, "public", layer, "geom", "gid")
                QgsProject.instance().addMapLayer(vlayer, False) 
                arheo_group.insertChildNode(7, QgsLayerTreeLayer(vlayer))  


            vlayer = postgis_connect(self, "public", "RKD", "geom", "id")
            QgsProject.instance().addMapLayer(vlayer, False)   
            arheo_group.insertChildNode(8, QgsLayerTreeLayer(vlayer)) 
        else:
                pass

        evrd = styles_path/'eVRD.qlr'
        QgsLayerDefinition().loadLayerDefinition(str(evrd), QgsProject.instance(), arheo_group)


        #Load Prostorske enote layes group
        if self.dlg.prostorske_enote.isChecked():
            self.iface.messageBar().pushMessage("Nalagam Prostoske enote...")
            if not root.findGroup("Prostorske enote"):
                prostorske_group = root.addGroup("Prostorske enote")
            else:
                prostorske_group = root.findGroup("Prostorske enote")

            prostorske = styles_path/'Prostorske enote.qlr'
            QgsLayerDefinition().loadLayerDefinition(str(prostorske), QgsProject.instance(), prostorske_group)
           
        else:
            self.iface.messageBar().pushMessage("Ne nalagam Prostorskih enot!", duration=2)       

        #Load Historične podlage layes group
        if self.dlg.historicnepodlage.isChecked():
            self.iface.messageBar().pushMessage("Historične podlage")
            if not root.findGroup("Historične podlage"):
                hist_group = root.addGroup("Historične podlage")
            else:
                hist_group = root.findGroup("Historične podlage")

            histo = styles_path/'Historicne podlage.qlr'
            QgsLayerDefinition().loadLayerDefinition(str(histo), QgsProject.instance(), hist_group)
            hist_group.setExpanded(False)
        else:
            self.iface.messageBar().pushMessage("Ne nalagam Prostorskih enot!", duration=2)  

        #Load podlage layes group
        if self.dlg.c_podlage.isChecked():
            self.iface.messageBar().pushMessage("Nalagam podlage..")
            if not root.findGroup("Podlage"):
                podlage_group = root.addGroup("Podlage")
            else:
                podlage_group = root.findGroup("Podlage")

            if access(self):
                podlage_zls = styles_path/'ZLS 1.qlr'
                QgsLayerDefinition().loadLayerDefinition(str(podlage_zls), QgsProject.instance(), podlage_group)
            else:
                pass

            podlage_gurs = styles_path/'GURS.qlr'
            QgsLayerDefinition().loadLayerDefinition(str(podlage_gurs), QgsProject.instance(), podlage_group)

        else:
            self.iface.messageBar().pushMessage("Ne nalagam podlag!", duration=2)


        QgsProject.instance().setCrs(crs)
        self.iface.messageBar().pushMessage("Nastavljam Državni kordinatni sistem D96/TM..", duration=5)  

        
        #Set which layers should not be expanded
        not_expanded = ['RKD', 'SMAP', 'ZLS interpretacija','Claustra Alpium Iuliarum', 'Načrti najdišč', 'Načrti najdišč_poligoni', 'Evidenca arheoloških raziskav', "Katalog najdišč"]
        for layer in not_expanded:
            layer = QgsProject.instance().mapLayersByName(layer)[0]
            myLayerNode = root.findLayer(layer.id())
            myLayerNode.setExpanded(False)

        #toggle visibility
        layers =['RKD','Claustra Alpium Iuliarum', 'Načrti najdišč', 'Načrti najdišč_poligoni', 'Evidenca arheoloških raziskav','SMAP', 'ZLS interpretacija']
        for layer in layers:
            layer = QgsProject.instance().mapLayersByName(layer)[0]
            root.findLayer(layer.id()).setItemVisibilityChecked(0)
                