# -*- coding: utf-8 -*-
"""
/***************************************************************************
 CreateLinkset / CreateLinksetDialog
                                 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
from PyQt5.QtWidgets import QTableWidgetItem


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


class CreateLinksetDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, plugin):
        """Constructor."""
        super(CreateLinksetDialog, 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.plugin = plugin
        
        # EXTREMELY IMPORTANT VARIABLE IF windowProcess NOT STOCK HE CAN'T USE POSTPROCESSALGORITHM()
        self.windowProcess = None

        """Connect the button to execute the 'select_cost_file' function after click"""
        self.extFilePushButton.clicked.connect(self.select_cost_file)
        # links specifics buttons that can show other items if it's selected
        self.euclidRadioButton.clicked.connect(self.hideAll)
        self.costRadioButton.clicked.connect(self.showTabCodes)
        self.extRadioButton.clicked.connect(self.showExternalFileResearch)
        self.projectComboBox.currentIndexChanged.connect(self.select_project)

        self.hideAll()
        
    #--------------------------------------------------------------------------
    
    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.createLinkset()

    # --------------------------------------------------------------------------
    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].project

        # find a non-use linkset name
        basicName = "newLinkset"
        counter = 1
        while (basicName + str(counter)) in [linkset.name for linkset in project.costLinks]:
            counter += 1

        # set the default graph name found
        self.nameLineEdit.setText(basicName + str(counter))

        # init specific items like cost tab and ext cost file researcher
        self.initCostTab(project)

    #--------------------------------------------------------------------------
    def initCostTab(self, project):
        """Initialize the cost tab with the selected project values where a Linkset will be created"""
        # set default value of cost table
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(len(project.codes))
        self.tableWidget.setHorizontalHeaderLabels(["Code", "Value"])
        
        # Fill lines
        counter = 0
        for code in project.codes:
            self.tableWidget.setItem(counter, 0, QTableWidgetItem(str(code)))
            self.tableWidget.setItem(counter, 1, QTableWidgetItem("1"))
            counter += 1

    #--------------------------------------------------------------------------
    
    def select_cost_file(self):
        """Open a window to select the external cost file for the Linkset"""
        
        # open a window to select the project
        filename, _filter = QFileDialog.getOpenFileName(self, "Select external cost file ","", '*.tif')

        # when you close the window but you haven't select a file
        if filename is not None:
            self.extFileLineEdit.setText(filename)

        
    #--------------------------------------------------------------------------
    
    def hideAll(self):
        """Hide all items which are use for a cost Linkset"""
        self.tableWidget.hide()
        self.label_3.hide()
        self.extFileLineEdit.hide()
        self.extFilePushButton.hide()
        self.adjustSize()
    
    #--------------------------------------------------------------------------
    
    def showTabCodes(self):
        """Show items use for a Linkset with a cost tab"""
        self.hideAll()
        self.tableWidget.show()
        self.adjustSize()
        
    #--------------------------------------------------------------------------
    
    def showExternalFileResearch(self):
        """Show items use for a Linkset with external cost"""
        self.hideAll()
        self.label_3.show()
        self.extFileLineEdit.show()
        self.extFilePushButton.show()
        self.adjustSize()
    
    #--------------------------------------------------------------------------
    
    def createLinkset(self):
        """Get all parameters set by the user and send them to the processing to create a Linkset"""
        indProject = self.projectComboBox.currentIndex()
        pathProject = self.projects[indProject].projectFile

        # get linkset name
        linksetName = self.nameLineEdit.text()
        
        # get distance type of linkset and code if the distance is cost
        if self.euclidRadioButton.isChecked():
            # create readable parameters for processing
            params = {'INPUT' : pathProject,
                      'TYPE' : 0,
                      'NAME' : linksetName}
        
        elif self.costRadioButton.isChecked():
            # get all codes set into a string
            codesSTR = ''
            for i in range(0,self.tableWidget.rowCount()):
                codesSTR += self.tableWidget.item(i, 0).text() + '=' + self.tableWidget.item(i, 1).text() + ' '

            # create readable parameters for processing
            params = {'INPUT' : pathProject,
                      'TYPE' : 1,
                      'NAME' : linksetName,
                      'CODE' : codesSTR}
                      
        elif self.extRadioButton.isChecked():
            # create readable parameters for processing
            params = {'INPUT' : pathProject,
                      'TYPE' : 1,
                      'NAME' : linksetName,
                      'EXTCOST' : self.extFileLineEdit.text()}
        
        # call the process to create a linkset with all the parameters
        self.windowProcess = processing.createAlgorithmDialog("graphab:create_linkset", params)
        self.windowProcess.show()
        self.windowProcess.runAlgorithm()
    
