import os
from qgis.core import (
    QgsProcessingAlgorithm,
    QgsProcessingParameterFolder,
    QgsProcessingParameterRasterDestination
)
from qgis import processing


class FactorLandsat(QgsProcessingAlgorithm):

    INPUT_FOLDER = "INPUT_FOLDER"
    OUTPUT_RASTER = "OUTPUT_RASTER"

    def name(self):
        return "factor_landsat"

    def displayName(self):
        return "Factor de escala Landsat (Collection 2)"

    def group(self):
        return "Geomaticape"

    def groupId(self):
        return "geomaticape"

    def createInstance(self):
        return FactorLandsat()

    def initAlgorithm(self, config=None):

        self.addParameter(
            QgsProcessingParameterFolder(
                self.INPUT_FOLDER,
                "Carpeta con bandas SR_B1 a SR_B7"
            )
        )

        self.addParameter(
            QgsProcessingParameterRasterDestination(
                self.OUTPUT_RASTER,
                "Imagen multiespectral corregida"
            )
        )

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

        folder = self.parameterAsString(parameters, self.INPUT_FOLDER, context)
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT_RASTER, context)

        bandas = [
            "SR_B1.TIF",
            "SR_B2.TIF",
            "SR_B3.TIF",
            "SR_B4.TIF",
            "SR_B5.TIF",
            "SR_B6.TIF",
            "SR_B7.TIF"
        ]

        bandas_corregidas = []

        for banda in bandas:

            ruta = os.path.join(folder, banda)

            if not os.path.exists(ruta):
                raise Exception(f"No se encontró {banda}")

            salida_temp = os.path.join(folder, f"scaled_{banda}")

            processing.run(
                "gdal:rastercalculator",
                {
                    'INPUT_A': ruta,
                    'BAND_A': 1,
                    'FORMULA': '(A * 0.0000275) + (-0.2)',
                    'OUTPUT': salida_temp
                },
                context=context,
                feedback=feedback
            )

            bandas_corregidas.append(salida_temp)

        processing.run(
            "gdal:merge",
            {
                'INPUT': bandas_corregidas,
                'SEPARATE': True,
                'OUTPUT': output
            },
            context=context,
            feedback=feedback
        )

        return {self.OUTPUT_RASTER: output}

    def run(self):
        processing.execAlgorithmDialog(self)
