# -*- coding: utf-8 -*-
"""
/***************************************************************************
 CorridorDialog
                                 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

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


class CorridorDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, plugin):
        """Constructor."""
        super(CorridorDialog, 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.projectComboBox.currentIndexChanged.connect(self.select_project)
        self.unitComboBox.addItems(plugin.UNITS)

        self.plugin = plugin
        # 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.calcCorridor()
    
    #--------------------------------------------------------------------------
    
    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 combo box with all available linkset
        self.linksetComboBox.clear()
        self.linksetComboBox.addItems([linkset.name for linkset in project.project.costLinks])

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

    def calcCorridor(self):
        """Get all parameters set by the user and send them to the processing to calculate corridors"""
        # get the name of the linkset selected
        indProject = self.projectComboBox.currentIndex()
        pathProject = self.projects[indProject].projectFile
        linksetName = self.linksetComboBox.currentText()
        distmax = self.doubleSpinBox.value()
        distUnit = self.unitComboBox.currentIndex()
        
        # create readable parameters for processing
        params = {'INPUT' : pathProject,
                  'NAMELINKSET' : linksetName,
                  'DIST' : distmax,
                  'DISTUNIT' : distUnit}
        
        # call the process to create a graph with all the parameters
        self.windowProcess = processing.createAlgorithmDialog("graphab:calc_corridor", params)
        self.windowProcess.show()
        self.windowProcess.runAlgorithm()
