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

"""
/***************************************************************************
 CoastalVulnerability
                                 A QGIS plugin
 This plugin calculates Coastal Vulnerability Index
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2024-05-20
        copyright            : (C) 2024 by LocateIT
        email                : kevinkiprotich0089@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'LocateIT'
__date__ = '2024-05-20'
__copyright__ = '(C) 2024 by LocateIT'

# 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,
                       QgsProcessingParameterRasterLayer,
                       QgsProcessingParameterRasterDestination,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingMultiStepFeedback)
import processing

class CoastalVulnerabilityAlgorithm(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):
        self.addParameter(QgsProcessingParameterRasterLayer('mean_tide_range_m', 'Mean tide range (m)', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('mean_wave_height_m', 'Mean wave height (m)', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('relative_sealevel_rise_rate_mmyr', 'Relative sea-level rise rate (mm/yr)', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('shoreline_erosionaccretion_rate_myr', 'Shoreline erosion/Accretion rate (m/yr)', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('geomorphology', 'Geomorphology', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterLayer('coastal_slope_', 'Coastal slope (%)', defaultValue=None))
        self.addParameter(QgsProcessingParameterRasterDestination('CoastalVulnerabilityIndex', 'Coastal Vulnerability Index', createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, feedback):
        feedback = QgsProcessingMultiStepFeedback(6, feedback)
        results = {}
        outputs = {}

        # Relative sea-level rise rate resampled
        alg_params = {
            'CELL_SIZE_X': None,
            'CELL_SIZE_Y': None,
            'CRS': None,
            'EXTENT': None,
            'GRID_OFFSET_X': None,
            'GRID_OFFSET_Y': None,
            'INPUT': parameters['relative_sealevel_rise_rate_mmyr'],
            'REFERENCE_LAYER': parameters['geomorphology'],
            'RESAMPLING_METHOD': 0,  # Nearest Neighbour
            'RESCALE': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RelativeSealevelRiseRateResampled'] = processing.run('native:alignsingleraster', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Mean tide range resampled
        alg_params = {
            'CELL_SIZE_X': None,
            'CELL_SIZE_Y': None,
            'CRS': None,
            'EXTENT': None,
            'GRID_OFFSET_X': None,
            'GRID_OFFSET_Y': None,
            'INPUT': parameters['mean_tide_range_m'],
            'REFERENCE_LAYER': parameters['geomorphology'],
            'RESAMPLING_METHOD': 0,  # Nearest Neighbour
            'RESCALE': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['MeanTideRangeResampled'] = processing.run('native:alignsingleraster', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Coastal_slope_resampled
        alg_params = {
            'CELL_SIZE_X': None,
            'CELL_SIZE_Y': None,
            'CRS': None,
            'EXTENT': None,
            'GRID_OFFSET_X': None,
            'GRID_OFFSET_Y': None,
            'INPUT': parameters['coastal_slope_'],
            'REFERENCE_LAYER': parameters['geomorphology'],
            'RESAMPLING_METHOD': 0,  # Nearest Neighbour
            'RESCALE': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Coastal_slope_resampled'] = processing.run('native:alignsingleraster', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # mean wave height resampled
        alg_params = {
            'CELL_SIZE_X': None,
            'CELL_SIZE_Y': None,
            'CRS': None,
            'EXTENT': None,
            'GRID_OFFSET_X': None,
            'GRID_OFFSET_Y': None,
            'INPUT': parameters['mean_wave_height_m'],
            'REFERENCE_LAYER': parameters['geomorphology'],
            'RESAMPLING_METHOD': 0,  # Nearest Neighbour
            'RESCALE': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['MeanWaveHeightResampled'] = processing.run('native:alignsingleraster', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # shoreline change resampled
        alg_params = {
            'CELL_SIZE_X': None,
            'CELL_SIZE_Y': None,
            'CRS': None,
            'EXTENT': None,
            'GRID_OFFSET_X': None,
            'GRID_OFFSET_Y': None,
            'INPUT': parameters['shoreline_erosionaccretion_rate_myr'],
            'REFERENCE_LAYER': parameters['geomorphology'],
            'RESAMPLING_METHOD': 0,  # Nearest Neighbour
            'RESCALE': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ShorelineChangeResampled'] = processing.run('native:alignsingleraster', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Raster calculator
        alg_params = {
            'BAND_A': 1,
            'BAND_B': 1,
            'BAND_C': 1,
            'BAND_D': 1,
            'BAND_E': 1,
            'BAND_F': 1,
            'EXTENT_OPT': 0,  # Ignore
            'EXTRA': '',
            'FORMULA': "sqrt((A*B*C*D*E*F)/6)",
            'INPUT_A': parameters['geomorphology'],
            'INPUT_B': outputs['Coastal_slope_resampled']['OUTPUT'],
            'INPUT_C': outputs['RelativeSealevelRiseRateResampled']['OUTPUT'],
            'INPUT_D': outputs['ShorelineChangeResampled']['OUTPUT'],
            'INPUT_E': outputs['MeanTideRangeResampled']['OUTPUT'],
            'INPUT_F': outputs['MeanWaveHeightResampled']['OUTPUT'],
            'NO_DATA': None,
            'OPTIONS': '',
            'PROJWIN': parameters['geomorphology'],
            'RTYPE': 5,  # Float32
            'OUTPUT': parameters['CoastalVulnerabilityIndex']
        }
        outputs['RasterCalculator'] = processing.run('gdal:rastercalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['CoastalVulnerabilityIndex'] = outputs['RasterCalculator']['OUTPUT']
        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 'Coastal Vulnerability Index'

    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 'Coastal Erosion'

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

    def createInstance(self):
        return CoastalVulnerabilityAlgorithm()
