# -*- coding: utf-8 -*-
"""
/***************************************************************************
 CalculateMetrics / CalculateMetricsDialog
                                 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
import processing

from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtWidgets import QFileDialog

# 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', 'calculate_metrics_dialog.ui'))


class CalculateMetricDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, metricsNames, typeMetrics, plugin):
        """Constructor."""
        super(CalculateMetricDialog, 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)

        self.metricsNames = metricsNames
        self.typeMetrics = typeMetrics
        
        self.plugin = plugin
        self.projectComboBox.currentIndexChanged.connect(self.select_project)
        self.metricComboBox.addItems(self.metricsNames)
        self.metricComboBox.currentIndexChanged.connect(self.updateDPParameters)
        self.unitComboBox.addItems(plugin.UNITS)
        self.pComboBox.addItems(plugin.PROBA_DIST)

        # EXTREMELY IMPORTANT VARIABLE IF windowProcess NOT STOCK HE CAN'T USE POSTPROCESSALGORITHM()
        self.windowProcess = None
        
    #--------------------------------------------------------------------------
    
    def showDialog(self):
        """Initialize basic window and waiting for any action of the user"""
        if not self.plugin.java:
            self.plugin.showJavaNotFound()
            return
        # upgrade the list of loaded project
        self.projects = self.plugin.getProjects()
        if len(self.projects) == 0:
            return

        self.projectComboBox.clear()
        self.projectComboBox.addItems([prj.project.name for prj in self.projects])
        self.adjustSize()
        self.show()

        result = self.exec_()
        # See if OK was pressed
        if result:
            # get all parameters set
            self.calcMetric()

    
    #--------------------------------------------------------------------------
    
    def select_project(self, index):
        """Open a window to select a project if there is no project selected yet and 
        initialize some items with project values"""

        project = self.projects[index]

        # populate the combobox with graphs and show it
        self.graphComboBox.clear()
        self.graphComboBox.addItems([graph.name for graph in project.project.graphs])

    #--------------------------------------------------------------------------
    
    def calcMetric(self):
        """Get all parameters set by the user and send them to the processing to calculate metrics"""
        indProject = self.projectComboBox.currentIndex()
        pathProject = self.projects[indProject].projectFile

        # get name of the selected graph
        graphName = self.graphComboBox.currentText()
        
        # get shortcut metrics name selected
        selectedMetricsNameIndex = self.metricComboBox.currentIndex()
        
        #get value of d parameters
        dValue = self.doubleSpinBox.value()
        distUnit = self.unitComboBox.currentIndex()

        #get selected value for p parameter
        selectedpValueIndex = self.pComboBox.currentIndex()
        
        # create readable parameters for processing
        params = {'INPUT' : pathProject,
                  'GRAPHNAME' : graphName,
                  'METRICSNAME' : selectedMetricsNameIndex,
                  'DPARAMETER' : dValue,
                  'DISTUNIT' : distUnit,
                  'PPARAMETER' : selectedpValueIndex}
        
        # call the process to create a graph with all the parameters
        if self.typeMetrics == 0:
            self.windowProcess = processing.createAlgorithmDialog("graphab:global_metric", params)
        else:
            self.windowProcess = processing.createAlgorithmDialog("graphab:local_metric", params)
        self.windowProcess.show()
        self.windowProcess.runAlgorithm()
    
    #--------------------------------------------------------------------------
    
    def updateDPParameters(self):
        """Hide or show items depending a selected parameter in a combo box"""
        # get shortcut metrics name selected
        metricsName = self.metricsNames[self.metricComboBox.currentIndex()]
        
        if metricsName == 'IIC':
            # hide useless parameters if IIC metric is selected
            self.label_4.hide()
            self.doubleSpinBox.hide()
            self.label_5.hide()
            self.pComboBox.hide()
            self.unitComboBox.hide()
            self.adjustSize()
        else:
            # show parameter if IIC metric is not selected
            self.label_4.show()
            self.doubleSpinBox.show()
            self.label_5.show()
            self.pComboBox.show()
            self.unitComboBox.show()
