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

"""
/***************************************************************************
 GeoQ
                                 A QGIS plugin
 Complemento para el modelado de escorrentía superficial
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-12-13
        copyright            : (C) 2021 by Fabio Alejandro Montealegre Medina - Fernanda Julia Gaspari / CEIDE-UNLP-CIC
        email                : fabio.montealegre@agro.unlp.edu.ar
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Fabio Alejandro Montealegre Medina- Fernanda Julia Gaspari / CEIDE-UNLP-CIC'
__date__ = '2021-12-13'
__copyright__ = '(C) 2021 by Fabio Alejandro Montealegre - Fernanda Julia Gaspari / CEIDE-UNLP-CIC'

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

__revision__ = '$Format:%H$'

import os
import inspect
from qgis.PyQt.QtGui import QIcon

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingMultiStepFeedback,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterVectorLayer,
                       QgsVectorLayer,
                       QgsProcessingParameterFileDestination)
import processing

class GeoQAlgorithm(QgsProcessingAlgorithm):

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

    OUTPUT = 'OUTPUT'
    INPUT = 'INPUT'

    def initAlgorithm(self, config=None):

        # We add the input vector features source. It can have any kind of
        # geometry.
        self.addParameter(QgsProcessingParameterNumber('PPmm', 'PP(mm)', type=QgsProcessingParameterNumber.Double, minValue=0, maxValue=1e+08, defaultValue=None))
        self.addParameter(QgsProcessingParameterVectorLayer('Suelos', 'Suelos', types=[QgsProcessing.TypeVectorAnyGeometry], defaultValue=None))
        self.addParameter(QgsProcessingParameterVectorLayer('Vegetacion', 'Vegetación', types=[QgsProcessing.TypeVectorAnyGeometry], defaultValue=None))
        self.addParameter(QgsProcessingParameterVectorLayer('v', 'Condición de Humedad', types=[QgsProcessing.TypeVector], defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Geoq', 'GeoQ', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Cf', 'CF', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=False, supportsAppend=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Ce', 'CE', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Cio', 'CIo', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, feedback):
        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        feedback = QgsProcessingMultiStepFeedback(19, feedback)
        results = {}
        outputs = {}

        # Intersección
        alg_params = {
            'INPUT': parameters['Suelos'],
            'INPUT_FIELDS': [''],
            'OVERLAY': parameters['Vegetacion'],
            'OVERLAY_FIELDS': [''],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Interseccin'] = processing.run('native:intersection', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Precipitación (PP)
        alg_params = {
            'FIELD_LENGTH': 5,
            'FIELD_NAME': 'PP(mm)',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': parameters['PPmm'],
            'INPUT': outputs['Interseccin']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['PrecipitacinPp'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Área
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'Area_ha',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': ' $area /10000',
            'INPUT': outputs['PrecipitacinPp']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Rea'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Código NC
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'Cod_NC',
            'FIELD_PRECISION': 3,
            'FIELD_TYPE': 1,
            'FORMULA': '\"Cod_Sue\" + \"Cod_Veg\"',
            'INPUT': outputs['Rea']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['CdigoNc'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # Unión tabla NC
        alg_params = {
            'DISCARD_NONMATCHING': False,
            'FIELD': 'Cod_NC',
            'FIELDS_TO_COPY': ['NC'],
            'FIELD_2': 'Cod_NC',
            'INPUT': outputs['CdigoNc']['OUTPUT'],
            'INPUT_2': parameters['v'],
            'METHOD': 1,
            'PREFIX': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['UninTablaNc'] = processing.run('native:joinattributestable', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(5)
        if feedback.isCanceled():
            return {}

        # Potencial Retención (S)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'S',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': '254*((100/\"NC\")-1)',
            'INPUT': outputs['UninTablaNc']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['PotencialRetencinS'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(6)
        if feedback.isCanceled():
            return {}

        # Abstracciones Iniciales (Io)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'Io',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': '\"S\"*0.2',
            'INPUT': outputs['PotencialRetencinS']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['AbstraccionesInicialesIo'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(7)
        if feedback.isCanceled():
            return {}

        # Coeficiente Abstracciones (CIo)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'CIo',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': 'Case when \"Io\"<\"PP(mm)\" then ((\"Io\"/\"PP(mm)\")*100)\r\n\tWhen \"Io\">\"PP(mm)\" then 100\r\nend\r\n',
            'INPUT': outputs['AbstraccionesInicialesIo']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['CoeficienteAbstraccionesCio'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(8)
        if feedback.isCanceled():
            return {}

        # Escorrentía (Q)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'Q(mm)',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': '\r\nCase when \"Io\"<\"PP(mm)\" then ((\"PP(mm)\"-(0.2* \"S\"))^ 2)/(\"PP(mm)\" +(0.8* \"S\"))\r\n\tWhen \"Io\">\"PP(mm)\" then 0\r\nend\r\n',
            'INPUT': outputs['CoeficienteAbstraccionesCio']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['EscorrentaQ'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(9)
        if feedback.isCanceled():
            return {}

        # Coeficiente Escurrimiento (CE)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'CE',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': '((\"Q(mm)\"/\"PP(mm)\")*100)',
            'INPUT': outputs['EscorrentaQ']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['CoeficienteEscurrimientoCe'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(10)
        if feedback.isCanceled():
            return {}

        # Infiltración (F)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'F(mm)',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': 'Case when \"Io\"<\"PP(mm)\" then (\"S\"*(\"PP(mm)\"-\"Io\")/(\"PP(mm)\"-\"Io\"+\"S\"))\r\n\tWhen \"Io\">\"PP(mm)\" then 0\r\nend\r\n\r\n',
            'INPUT': outputs['CoeficienteEscurrimientoCe']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['InfiltracinF'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(11)
        if feedback.isCanceled():
            return {}

        # Coeficiente Infiltración (CF)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': 'CF',
            'FIELD_PRECISION': 2,
            'FIELD_TYPE': 0,
            'FORMULA': 'Case when \"Io\"<\"PP(mm)\" then ((\"F(mm)\"/\"PP(mm)\")*100)\r\n\tWhen \"Io\">\"PP(mm)\" then 0\r\nend\r\n',
            'INPUT': outputs['InfiltracinF']['OUTPUT'],
            'OUTPUT': parameters['Geoq']
            #setstyleforvectorlayer
        }
        outputs['CoeficienteInfiltracinCf'] = processing.run('native:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Geoq'] = outputs['CoeficienteInfiltracinCf']['OUTPUT']

        feedback.setCurrentStep(12)
        if feedback.isCanceled():
            return {}

        # CE
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '\"CE\"','length': 5,'name': 'CE','precision': 2,'type': 6}],
            'INPUT': outputs['CoeficienteInfiltracinCf']['OUTPUT'],
            'OUTPUT': parameters['Ce']
        }
        outputs['Ce'] = processing.run('native:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Ce'] = outputs['Ce']['OUTPUT']

        feedback.setCurrentStep(13)
        if feedback.isCanceled():
            return {}

        # Simbología CE
        alg_params = {
            'INPUT': outputs['Ce']['OUTPUT'],
            'STYLE': 'C:\\GeoQ\\CE_azules.qml'
        }
        outputs['SimbologaCe'] = processing.run('qgis:setstyleforvectorlayer', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(14)
        if feedback.isCanceled():
            return {}

        # CF
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '\"CF\"','length': 5,'name': 'CF','precision': 2,'type': 6}],
            'INPUT': outputs['CoeficienteInfiltracinCf']['OUTPUT'],
            'OUTPUT': parameters['Cf']
        }
        outputs['Cf'] = processing.run('native:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Cf'] = outputs['Cf']['OUTPUT']

        feedback.setCurrentStep(15)
        if feedback.isCanceled():
            return {}

        # Simbología CF
        alg_params = {
            'INPUT': outputs['Cf']['OUTPUT'],
            'STYLE': 'C:\\GeoQ\\CF_marrores.qml'
        }
        outputs['SimbologaCf'] = processing.run('qgis:setstyleforvectorlayer', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(16)
        if feedback.isCanceled():
            return {}

        # CIo
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '\"CIo\"','length': 5,'name': 'CIo','precision': 2,'type': 6}],
            'INPUT': outputs['CoeficienteInfiltracinCf']['OUTPUT'],
            'OUTPUT': parameters['Cio']
        }
        outputs['Cio'] = processing.run('native:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Cio'] = outputs['Cio']['OUTPUT']

        feedback.setCurrentStep(17)
        if feedback.isCanceled():
            return {}

        # Simbología CIo
        alg_params = {
            'INPUT': outputs['Cio']['OUTPUT'],
            'STYLE': 'C:\\GeoQ\\CIo_verdes.qml'
        }
        outputs['SimbologaCio'] = processing.run('qgis:setstyleforvectorlayer', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        return results

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

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

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr(self.groupId())

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return ''

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def icon(self):
        cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
        icon = QIcon(os.path.join(os.path.join(cmd_folder, 'logo-mich.png')))
        return icon

    def createInstance(self):
        return GeoQAlgorithm()
