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

"""
/***************************************************************************
 PipelineEngineer
                                 A QGIS plugin
 A collection of Pipeline Engineering Tools.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-12-06
        copyright            : (C) 2025 by Pipeline Engineer
        email                : info@pipelineengineer.com.au
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Pipeline Engineer'
__date__ = '2025-12-06'
__copyright__ = '(C) 2025 by Pipeline Engineer'

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

__revision__ = '$Format:%H$'

import os

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
    QgsProcessing,
    QgsFeatureSink,
    QgsProcessingAlgorithm,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterFeatureSink,
    QgsProcessingParameterField,
    QgsFeatureRequest,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterNumber,
    QgsProcessingParameterVectorLayer,
    QgsProcessingParameterMultipleLayers,
    QgsProcessingParameterEnum,
    QgsProcessingOutputString,
    QgsProcessingException,
    QgsProcessingOutputMultipleLayers,
    QgsProcessingParameterFileDestination
)

from qgis.PyQt.QtGui import QIcon

from .logic.running_dc_powerflow import *

class runDCPowerFlowAlgorithm(QgsProcessingAlgorithm):

    NET_LAYERS = 'NET_LAYERS'
    LOAD_LAYERS = 'LOAD_LAYERS'
    OUTPUT = 'OUTPUT'
    
    def initAlgorithm(self, config):

        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                name=self.NET_LAYERS,
                description='Network Layers',
                layerType=QgsProcessing.TypeVector
            )
        )

        #

        self.addParameter(QgsProcessingParameterBoolean(
            self.LOAD_LAYERS, 'Load Layers?',
            defaultValue=True
        ))

        # Output: list of layer IDs
        self.addParameter(QgsProcessingParameterFileDestination(
                self.OUTPUT,
                'Output GeoPackage',
                fileFilter='GeoPackage (*.gpkg)'
            )
        )

    # -------------------------------------------------------
    # PROCESS
    # -------------------------------------------------------

    def processAlgorithm(self, parameters, context, feedback):

        # MULTIPLE LAYERS
        layers = self.parameterAsLayerList(parameters, self.NET_LAYERS, context)

        if not layers:
            raise QgsProcessingException("No valid input layers selected.")

        # Extract all parameters
        # Read parameters from user input
        net_layers = self.parameterAsLayerList(parameters, self.NET_LAYERS, context)
        load_layers = self.parameterAsBool(parameters, self.LOAD_LAYERS, context)

        #algorithms = ["nr", "iwamoto_mr","bfsw","gs","fdbx","fdxb"]      
        #inits = ["auto","flat","dc","results"]
        #trafo_models = ["t","pi"]
        #trafo_loadings = ["current","power"]
        
        #algorithm = algorithms[algorithm_index]
        #init = inits[init_index]
        #trafo_model = trafo_models[trafo_model_index]
        #trafo_loading = trafo_loadings[trafo_loading_index]

        gpkg_path = self.parameterAsFileOutput(
                                                parameters,
                                                self.OUTPUT,
                                                context
                                            )

        # Run your solver
        feedback.pushInfo("Running powerflow solver…")

        result_layers = run_dc_powerflow(
            layers=layers,
            load_layers=load_layers
        )

        processing.run("native:package", 
                    {'LAYERS':result_layers,
                     'OUTPUT':gpkg_path,
                     'OVERWRITE':False,
                     'SAVE_STYLES':True,
                     'SAVE_METADATA':True,
                     'SELECTED_FEATURES_ONLY':False,
                     'EXPORT_RELATED_LAYERS':False}
                   )

        return {}
        
    # -------------------------------------------------------

    def name(self):
        return 'pandapower_dc_powerflow'

    def displayName(self):
        return self.tr('Run DC Powerflow')

    def group(self):
        return self.tr(self.groupId())

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

    def shortHelpString(self):
        return self.tr("Runs an DC powerflow for selected layers using pandapower.")

    def createInstance(self):
        return runDCPowerFlowAlgorithm()
