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

"""
/***************************************************************************
 CalculateMetrics
                                 A QGIS plugin
 Process that able you to calculate metrics for Graphab Graph
 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,
                       QgsProcessingOutputNumber)

# import subprocess
import os

from .GraphabAlgoProcessing import GraphabAlgoProcessing


class CalculateGlobalMetric(GraphabAlgoProcessing):
    """
    Processing algorithm use to calculate metrics. 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'
    GRAPHNAME = 'GRAPHNAME'
    METRICSNAME = 'METRICSNAME'
    DPARAMETER = 'DPARAMETER'
    PPARAMETER = 'PPARAMETER'
    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 name of the selected Graph
        self.addParameter(
            QgsProcessingParameterString(
                self.GRAPHNAME,
                self.translate('py', 'Graph name'),
                optional=False
            )
        )
        
        # Input for the shortcut name of metrics
        self.addParameter(
            QgsProcessingParameterEnum(
                self.METRICSNAME,
                self.translate('py', 'Global metric'),
                self.plugin.GMETRICS,
                allowMultiple=False,
                defaultValue=0
            )
        )

        # 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 the d parameter
        self.addParameter(
            QgsProcessingParameterNumber(
                self.DPARAMETER,
                self.translate('py', 'Distance'),
                type=QgsProcessingParameterNumber.Double,
                minValue=0.0,
                defaultValue=1000.0,
                optional=False
            )
        )
        
        # Input for the p parameter
        self.addParameter(
            QgsProcessingParameterEnum(self.PPARAMETER,
                self.translate('py', 'Probability'),
                self.plugin.PROBA_DIST,
                allowMultiple=False,
                defaultValue=0
            )
        )
        
        # Metric result
        self.addOutput(
            QgsProcessingOutputNumber(
                'OUTPUT',
                self.translate('py', 'Global Metric value')
            )
        )


    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)
        graphName = self.parameterAsString(parameters, self.GRAPHNAME, context)
        metricsName = self.plugin.GMETRICS[self.parameterAsInt(parameters, self.METRICSNAME, context)]
        dValue = self.parameterAsDouble(parameters, self.DPARAMETER, context)
        distUnit = self.parameterAsInt(parameters, self.DISTUNIT, context)
        pValue = self.plugin.PROBA_DIST[self.parameterAsInt(parameters, self.PPARAMETER, context)]
        
        project = os.path.normcase(r''+project)
            
        commandToExec = ['--project', project, '--usegraph', graphName, '--gmetric', metricsName]
        
        if metricsName != 'IIC':
            strDist = str(dValue)
            if distUnit == 0:
                strDist = '{' + strDist + '}'
            commandToExec += ['d=' + strDist, 'p=' + pValue]

        super().processAlgorithm(commandToExec, context, feedback)
        
        if self.executionError:
            return {}
        else:
            metricFile = os.path.join(os.path.dirname(project), metricsName + ".txt")
            f = open(metricFile, "r")
            f.readline()
            if metricsName != 'IIC':
                metricValue = float(f.readline().split("\t")[3])
            else:
                metricValue = float(f.readline().split("\t")[1])
            f.close()
            return {'OUTPUT': metricValue }

    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 'global_metric'

    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', 'Calculate Global Metric')

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