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

"""
/***************************************************************************
 dbpriskapp
                                 A QGIS plugin
 dbpriskapp
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-06-12
        copyright            : (C) 2025 by KIOS Smart Water Team
        email                : mkiria01@ucy.ac.cy
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'KIOS Smart Water Team'
__date__ = '2025-06-12'
__copyright__ = '(C) 2025 by KIOS Smart Water Team'

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

__revision__ = '$Format:%H$'

import json
import os
import  subprocess

try:
 import pandas as pd
except ImportError:
    subprocess.check_call(['pip', 'install', 'pandas>=1.5.3'])

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessingAlgorithm,
                       QgsProcessingParameterString)


class dbpriskappAlgorithm(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # 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):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # Add a parameter for a JSON-style dictionary string (optional)
        self.addParameter(
            QgsProcessingParameterString(
                name=self.INPUT,
                description='Input dictionary (as JSON)'
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        # import the module
        from dbpScenarioGenerator import WaterQualitySimulation

        # Read inline dictionary input (not used in this run mode, but kept for backward compatibility)
        dict_str = self.parameterAsString(parameters, 'INPUT', context)
        base_dir = os.path.dirname(os.path.dirname(__file__))
        for folder in ["dbpRisk2", "dbpSimulatorUI"]:
            plugin_dir = os.path.join(base_dir, folder)
            if os.path.exists(plugin_dir):
                break

        input_parameters = json.loads(dict_str)
        df = pd.read_excel(input_parameters["excel_file"], engine='openpyxl')
        input_parameters["excel_file"] = df
        input_parameters["feedback"] = feedback
        sim = WaterQualitySimulation(**input_parameters)
        sim.setup_simulation()
        [results, node_id, species_names_function, MSX_comps, global_times, soeciesnamesmsx,
         MSXunits, mes] = sim.run_simulation()
        summary_output_path = os.path.join(plugin_dir, "data", "tmp_data", "min_max_mean.xlsx")
        summary_output_path_uncertainty = os.path.join(plugin_dir, "data", "tmp_data", "min_max_mean_uncertainty.xlsx")
        sim.exportMSXstatistics(summary_output_path, nodeids=True, nodeindex=False)
        sim.exportMSXstatistics_uncertainty(summary_output_path_uncertainty, nodeids=True, nodeindex=False)

        self.OUTPUT = {
            "results": results,
            "node_id": node_id,
            "species_names_function": species_names_function,
            "Measured_Chlorine": mes,
            "Dataframe": sim.dataframe,
            "Dataframes": sim.dataframe_uncertainty,
            "MSX_comps": MSX_comps,
            "global_times": global_times,
            "soeciesnamesmsx": soeciesnamesmsx,
            "MSXunits": MSXunits,
            "Dataf": sim.dataf

        }

        return self.OUTPUT

    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 'dbpRisk Algorithm'

    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 createInstance(self):
        return dbpriskappAlgorithm()
