# -*- coding: utf-8 -*-

"""
/***************************************************************************
 CreateGraph
                                 A QGIS plugin
 Process that able you to create a Graph for Graphab
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-07-02
        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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'robin.marlinl@gmail.com'
__date__ = '2020-07-02'
__copyright__ = '(C) 2020 by ThéMA'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from qgis.core import (QgsProcessingParameterString,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterFile, QgsProcessingParameterEnum)

# import subprocess
import os

from .GraphabAlgoProcessing import GraphabAlgoProcessing

class CreateGraph(GraphabAlgoProcessing):
    """
    Processing algorithm use to create a new Graph. It inherit of GraphabAlgoProcessing
    that execute the command send by this class and it inherit of QgsProcessingAlgorithm
    """
    
    def __init__(self,plugin):
        super().__init__(plugin)

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    INPUT = 'INPUT'
    NAMEGRAPH = 'NAMEGRAPH'
    NAMELINKSET = 'NAMELINKSET'
    DIST = 'DIST'
    DISTUNIT = 'DISTUNIT'


    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # Input for the XML file that represent the Graphab Project
        self.addParameter(
            QgsProcessingParameterFile(
                self.INPUT,
                self.translate('py', 'XML project file'),
                fileFilter = 'xml(*.xml)',
                optional=False
            )
        )

        # Input for the Linkset name
        self.addParameter(
            QgsProcessingParameterString(
                self.NAMELINKSET,
                self.translate('py', 'Linkset name'),
                optional=False
            )
        )

        # Input for the Graph name
        self.addParameter(
            QgsProcessingParameterString(
                self.NAMEGRAPH,
                self.translate('py', 'Graph name'),
                optional=True
            )
        )

        # Unit of the distance
        self.addParameter(
            QgsProcessingParameterEnum(
                self.DISTUNIT,
                self.translate('py', 'Distance unit'),
                self.plugin.UNITS,
                allowMultiple=False,
                defaultValue=0,
                optional=False
            )
        )

        # Input for Graph distance max
        # If value equals 0 -> non-thresholded graph
        self.addParameter(
            QgsProcessingParameterNumber(
                self.DIST,
                self.translate('py', 'Threshold distance for pruning (0 = no pruning)'),
                type=QgsProcessingParameterNumber.Double,
                minValue=0.0,
                defaultValue=0.0,
                optional=False
            )
        )


    def processAlgorithm(self, parameters, context, feedback):
        """
        Create a command line depending of parameters set by the user and send it to its parent 
        to execute it
        """

        # Get all parameter set
        project = self.parameterAsFile(parameters, self.INPUT, context)
        self.graphName = self.parameterAsString(parameters, self.NAMEGRAPH, context)
        linksetName = self.parameterAsString(parameters, self.NAMELINKSET, context)
        distanceMax = self.parameterAsDouble(parameters, self.DIST, context)
        distUnit = self.parameterAsInt(parameters, self.DISTUNIT, context)
        
        self.projectPath = os.path.normcase(r''+project)
        
        commandToExec = ['--project', self.projectPath, '--uselinkset', linksetName, '--graph']

        if self.graphName != '':
            commandToExec.append('name=' + self.graphName)
        
        if distanceMax > 0:
            strDist = str(distanceMax)
            if distUnit == 0:
                strDist = '{' + strDist + '}'
            commandToExec.append('threshold=' + strDist)
        
        commandToExec.append('--topo')
        
        super().processAlgorithm(commandToExec, context, feedback)
        
        return {}

    def postProcessAlgorithm(self, context, feedback):
        """After the execution of the processing, this function
        add and show the new Graph in the map. """
        project = self.plugin.projects[self.projectPath]
        if not (self.executionError or project is None):
            # if the project is already loaded add the Graph that has been created
            project.addGraphProject(self.graphName)

        return {}


    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'create_graph'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.translate('py', 'Create Graph')

    def createInstance(self):
        return CreateGraph(self.plugin)
