# -*- coding: utf-8 -*-
"""
/***************************************************************************
 GraphSymbology / GraphSymbologyDialog
                                 A QGIS plugin
 This plugin allows you to convert easly a Graphab project
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2020-04-20
        git sha              : $Format:%H$
        copyright            : (C) 2020 by ThéMA
        email                : robin.marlinl@gmail.com
        author               : Robin Marlin-Lefebvre
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os

from PyQt5.QtWidgets import QMessageBox
from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from qgis.core import QgsProject

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'ui_files', 'graph_symbology_dialog.ui'))

class GraphSymbologyDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, plugin):
        """Constructor."""
        super(GraphSymbologyDialog, self).__init__(None)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        # Link the window to the main object (Graphab) for shared variables
        self.plugin = plugin
        self.projectGroup = None
        # populate the combobox with existing style files names
        self.colorComboBox.addItems(self.plugin.stylesTabUnabled)

        self.graphComboBox.currentIndexChanged.connect(self.selectGraph)
        
    #--------------------------------------------------------------------------
    
    def showDialog(self):
        """Open a dialog window to choose a Graph (if it is not done yet) of a specific Project and 
        paramters like the color ramp of circles, the scale size, the field what color depends and if 
        the size depends of  the Capacity of circles or not."""

        # Verif if a Project has been deleted
        projects = self.plugin.getProjects()
        self.projectGroup = None

        # Get the current selected layer if it exist
        nodeSelected = self.plugin.iface.layerTreeView().currentNode()
        graphGroup = None
        for project in projects:
            for graph in project.project.graphs:
                if nodeSelected.name() == graph.name:
                    graphGroup = nodeSelected
                    self.projectGroup = project.getProjectGroup()

        if self.projectGroup is None:
            if len(projects) == 1:
                self.projectGroup = projects[0].projectGroup
            elif "GraphabProject" in nodeSelected.customProperties():
                self.projectGroup = self.plugin.projects[nodeSelected.customProperty("GraphabProject")].projectGroup
            else:
                QMessageBox.information(self.plugin.iface.mainWindow(), "Graphab", "Select a graph or a project before.")
                return

        #populate the combobox with existing groups names
        # Verif if there is Graph availables and stop the function if not
        graphsName = [groupGraphLoop.name() for groupGraphLoop in self.projectGroup.children()[0].children()]
        if len(graphsName) == 0:
            QMessageBox.information(self.plugin.iface.mainWindow(), "Graphab",
                                    "There is no graph in selected project")
            return
        self.graphComboBox.clear()
        self.graphComboBox.addItems(graphsName)
        if graphGroup != None:
            try:
                self.graphComboBox.setCurrentIndex(self.projectGroup.children()[0].children().index(graphGroup))
            except:
                print("Wrong selected Graph group")

        #writing default value for min and max scale
        self.lineEdit.setText("1")
        self.lineEdit_2.setText("15")

        # show the dialog
        self.show()

        # Run the dialog event loop
        result = self.exec_()
        # See if OK was pressed
        if result:
            # change symbology of graph selected
            self.getInfoGraph()

    # --------------------------------------------------------------------------

    def selectGraph(self, index):
        # populate the combobox with existing fieldnames
        layer = self.projectGroup.children()[2].layer()
        graphName = self.graphComboBox.currentText()

        self.metricComboBox.clear()
        for field in layer.fields():
            if field.name().endswith("_"+graphName) or field.name() == "_Capacity":
                self.metricComboBox.addItems([field.name()])

    #--------------------------------------------------------------------------
    
    def getInfoGraph(self):
        """Get parameters entered by the user in the Symbology window and use them to change the symbology
        of the Graph selected."""

        # get fieldname choosen
        fieldname = self.metricComboBox.currentText()
        # get stylename choosen
        styleName = self.colorComboBox.currentText()
        minScale = None
        maxScale = None
        
        #get graphGroup choosen
        selectedgraphGroupIndex = self.graphComboBox.currentIndex()
        graphGroup = self.projectGroup.children()[0].children()[selectedgraphGroupIndex]

        # get nodes layer of the specific graphGroup
        layerGraph = graphGroup.children()[0]

        #get min and max scale
        minScaleTampon = self.lineEdit.text()
        if minScaleTampon.isnumeric():
            minScale = minScaleTampon

        maxScaleTampon = self.lineEdit_2.text()
        if maxScaleTampon.isnumeric():
            maxScale = maxScaleTampon

        #get a boolean if the checkbox is checked
        defaultSize = self.checkBox.isChecked()

        # Use paremeters to change the symbology of a specific Graph
        self.plugin.GraphabStyle.prepareStyle(fieldname, layerGraph.layer(), styleName, minScale, maxScale, defaultSize)

        # Set visible on the QGIS layer window the edited Graph
        layerGraph.setItemVisibilityChecked(True)
        graphGroup.setItemVisibilityChecked(True)

        # Expand the layer group
        graphGroup.setExpanded(True)
