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

"""
/***************************************************************************
 Prepare CoolParksTool
                                 A QGIS plugin
 This plugin prepare data for the CoolParksTool
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2023-07-06
        copyright            : (C) 2023 by Jérémy Bernard
        email                : jeremy.bernard@zaclys.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Jérémy Bernard'
__date__ = '2023-07-06'
__copyright__ = '(C) 2023 by Jérémy Bernard'

# 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, QVariant
from qgis.core import (QgsProcessing,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterField,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterMatrix,
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterString,
                       QgsProcessingParameterRasterLayer,
                       QgsProcessingParameterBoolean,
                       QgsRasterLayer,
                       QgsVectorLayer,
                       QgsProject,
                       QgsProcessingContext,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterFile,
                       QgsProcessingException,
                       QgsLayerTreeGroup)
# qgis.utils import iface
from pathlib import Path
from qgis.PyQt.QtGui import QIcon
import inspect
import unidecode
import geopandas as gpd

from .functions import mainCalculations
from .functions.globalVariables import *
from .functions import WriteMetadata
from .functions.DataUtil import trunc_to, round_to
from .functions.coolparks_postprocess import loadCoolParksRaster, loadCoolParksVector, Renamer


class CoolParksProcessorAlgorithm(QgsProcessingAlgorithm):
    """
    
    """

    # 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.

    # Input variables
    SCENARIO_DIRECTORY = "SCENARIO_DIRECTORY"
    WEATHER_FILE = "WEATHER_FILE"
    WEATHER_SCENARIO = "WEATHER_SCENARIO"
    OUTPUT_DIRECTORY = "OUTPUT_DIRECTORY"
    
    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        
        # We add the input parameters
        self.addParameter(
            QgsProcessingParameterString(
                self.WEATHER_SCENARIO,
                self.tr('Meteorological scenario name'),
                defaultValue = DEFAULT_WEATHER,
                optional = False)) 
        self.addParameter(
            QgsProcessingParameterFile(
                self.SCENARIO_DIRECTORY,
                self.tr(f'Directory of the scenario of interest (should contain two folders called "{OUTPUT_PREPROCESSOR_FOLDER}" and "{OUTPUT_PROCESSOR_FOLDER})"'),
                behavior=QgsProcessingParameterFile.Folder))
        self.addParameter(
            QgsProcessingParameterFile(
                self.WEATHER_FILE,
                self.tr('Input meteorological file (.txt or .csv)')))

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        
        # try:
        #     import jaydebeapi
        # except:
        #     raise QgsProcessingException("'jaydebeapi' Python package is missing.")
        
        scenarioDirectory = self.parameterAsString(parameters, self.SCENARIO_DIRECTORY, context)
        weatherFile = self.parameterAsString(parameters, self.WEATHER_FILE, context)
        weatherScenario = self.parameterAsString(parameters, self.WEATHER_SCENARIO, context)
        prefix = unidecode.unidecode(weatherScenario).replace(" ", "_")
        
        # Creates the output folder if it does not exist
        if os.path.exists(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER):
            if os.path.exists(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix):
                raise QgsProcessingException(f'"{prefix}" folder already exists in "{scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER}"')
            else:
                os.mkdir(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix)   
        else:
            raise QgsProcessingException(f'"{scenarioDirectory}" should contain a folder called "{OUTPUT_PROCESSOR_FOLDER}". It is not the directory of a preprocessed scenario.')
        

        # if feedback:
        #     feedback.setProgressText("Writing settings for this model run to specified output folder (Filename: RunInfoURock_YYYY_DOY_HHMM.txt)")
        # WriteMetadataURock.writeRunInfo(outputDirectory, build_file, heightBuild,
        #                                 veg_file, attenuationVeg, baseHeightVeg, topHeightVeg,
        #                                 z_ref, v_ref, windDirection, profileType,
        #                                 profileFile,
        #                                 meshSize, dz)
        
        if feedback:
            feedback.setProgressText("Calculate park effect on air temperature")
            if feedback.isCanceled():
                feedback.setProgressText("Calculation cancelled by user")
                return {}
        # Calculates the effect of the park on its surrounding
        output_t_path, output_dt_path, deltaT_min_value, deltaT_max_value = \
            mainCalculations.calcParkInfluence(weatherFilePath = weatherFile, 
                                               preprocessOutputPath = scenarioDirectory,
                                               prefix = prefix,
                                               feedback = feedback)
        
        if feedback:
            feedback.setProgressText("Calculate park effect on building energy and thermal comfort")
            if feedback.isCanceled():
                feedback.setProgressText("Calculation cancelled by user")
                return {}
        # Calculates the impact of the cooling on the buildings
        gdf_build, output_build_path = \
            mainCalculations.calcBuildingImpact(preprocessOutputPath = scenarioDirectory,
                                                prefix = prefix)
        
        ######################################################################
        ######################## LOAD DATA INTO QGIS #########################
        ######################################################################
        # Calculates the number of significant digits
        if NB_ISOVALUES < 10:
            sign_digits = 1
        else:
            sign_digits = 2
            
        # Load data into QGIS
        global layernames
        layernames = {}
        i = 0
        for tp in [DAY_TIME, NIGHT_TIME]:
            layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: Park impact on air temperature at {tp}:00 (°C)")
            # Load the vector layer with a given style
            loadCoolParksVector(filepath = output_dt_path[tp] + ".geojson",
                                layername = layernames[i],
                                variable = None,
                                subgroup = QgsLayerTreeGroup("parameter not used..."),
                                vector_min = deltaT_min_value,
                                vector_max = deltaT_max_value,
                                feedback = feedback,
                                context = context,
                                valueZero = 0,
                                opacity = DEFAULT_OPACITY)
            i += 1
        
        # Load building results into QGIS
        for var in BUILDING_LEGEND_PROCESS.index:
            layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: {BUILDING_LEGEND_PROCESS[var]}")
            loadCoolParksVector(filepath = output_build_path,
                                layername = layernames[i],
                                variable = var,
                                subgroup = QgsLayerTreeGroup("parameter not used..."),
                                vector_min = gdf_build[var].min(),
                                vector_max = gdf_build[var].max(),
                                feedback = feedback,
                                context = context,
                                valueZero = 0,
                                opacity = 1)
            i += 1
        
        # Return the output file names
        return {self.OUTPUT_DIRECTORY: scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix}


    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 'coolparkstool_process'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('2. Calculate park effects')

    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 shortHelpString(self):
        return self.tr('The CoolParksTool "2. Calculate park effects" module is used '+
                       'to calculate:\n'+
                       '    - the effect of the park composition on the cooling,\n'+
                       '    - the effect of the urban morphology on the transport of cool air,\n'+
                       '    - the effect of the cool air on building energy and building '+
                       '    thermal comfort\n'
        '\n'
        '\n'
        """You need to first use the '1. Prepare data' for each new scenario you 
        want to simulate."""
        '\n'
        '\n'
        '---------------\n'
        'Full manual available via the <b>Help</b>-button.')

    def helpUrl(self):
        url = "https://github.com/j3r3m1/coolparkstool"
        return url
    
    def icon(self):
        cmd_folder = Path(os.path.split(inspect.getfile(inspect.currentframe()))[0]).parent
        icon = QIcon(str(cmd_folder) + "/icons/urock.png")
        return icon

    def createInstance(self):
        return CoolParksProcessorAlgorithm()
