# -*- 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$'

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,
    QgsProcessingParameterString
)

from .logic.fluids import *

from qgis.PyQt.QtGui import QIcon

class AddFluidValueToLayer(QgsProcessingAlgorithm):

    INPUT = 'INPUT'
    OUTPUT = 'OUTPUT'
    PARAMETER = 'PARAMETER'
    PRES = 'PRES'
    TEMP = 'TEMP'
    FLUID = 'FLUID'
    ADD_FLUID = 'ADD_FLUID'

    def initAlgorithm(self, config):

        # Input line layer
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVector]
            )
        )

        self.addParameter(
            QgsProcessingParameterEnum(
                name=self.FLUID,
                description='Select Fluid',
                options=["hgas","lgas","hydrogen","methane","water",
                         "biomethane_pure","biomethane_treated","air"],
                defaultValue=0  
            )
        )

        self.addParameter(
            QgsProcessingParameterEnum(
                name=self.PARAMETER,
                description='Select Fluid Parameter',
                options=['compressibility','density','heat_capacity','molar_mass','viscosity'],
                defaultValue=1 
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                self.TEMP, 'Temperature',
                type=QgsProcessingParameterNumber.Double,
                minValue=0, maxValue=100000, defaultValue=293.15
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                self.PRES, 'Pressure',
                type=QgsProcessingParameterNumber.Double,
                minValue=0, maxValue=100000, defaultValue=1
            )
        )

        self.addParameter(QgsProcessingParameterBoolean(
            self.ADD_FLUID, 'Add Fluid?',
            defaultValue=True
        ))


        # Output
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Parameter Added')
            )
        )

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

        # Retrieve layer source
        source = self.parameterAsSource(parameters, self.INPUT, context)

        # Convert to a materialised QgsVectorLayer (so it can be processed normally)
        layer = source.materialize(QgsFeatureRequest())

        # Retrieve ID field selected by user

        parameter_index = self.parameterAsInt(parameters, self.PARAMETER, context)
        
        fluid_index = self.parameterAsInt(parameters, self.FLUID, context)
        
        fluids=["hgas","lgas","hydrogen","methane","water","biomethane_pure","biomethane_treated","air"]
        
        parameter_list = ['compressibility','density','heat_capacity','molar_mass','viscosity']
        
        chosen_fluid = fluids[fluid_index]

        temperature = self.parameterAsDouble(parameters, self.TEMP, context)
        
        pressure = self.parameterAsDouble(parameters, self.PRES, context)

        parameter = parameter_list[parameter_index]

        add_fluid = self.parameterAsBool(parameters, self.ADD_FLUID, context) 

        # Run your tee junction pipeline
        result_layer = add_fluid_params_to_layer(layer,chosen_fluid,parameter,temperature,pressure,add_fluid)

        # Create sink with the fields, geometry type and CRS of the output layer
        sink, dest_id = self.parameterAsSink(
            parameters,
            self.OUTPUT,
            context,
            result_layer.fields(),
            result_layer.wkbType(),
            result_layer.sourceCrs()
        )

        # Add resulting features to sink
        for f in result_layer.getFeatures():
            if feedback.isCanceled():
                break
            sink.addFeature(f, QgsFeatureSink.FastInsert)

        return {self.OUTPUT: dest_id}

    def name(self):
        return 'add_fluid_param'

    def displayName(self):
        return self.tr('Add Fluid Parameter to Layer')

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

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

    def shortHelpString(self):
        return self.tr("""
    Adds a fluid parameter of the selected layer to the attribute table.
    """)

    def createInstance(self):
        return AddFluidValueToLayer()