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

"""
Convert polygons to raster and save as a WEng .grd file
"""

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
    QgsProcessing,
    QgsProcessingException,
    QgsProcessingAlgorithm,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterFileDestination,
    QgsProcessingParameterNumber
)
from qgis import processing
import os, inspect


class SaveRoughnessRaster(QgsProcessingAlgorithm):
    """
    This scripts saves roughness polygons as a WEng .grd file
    """

    # 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 = "INPUT"
    OUTPUT = "OUTPUT"
    VALUE = "grid_spacing"

    def tr(self, string):
        """
        Returns a translatable string with the self.tr() function.
        """
        return QCoreApplication.translate("Processing", string)

    def createInstance(self):
        return SaveRoughnessRaster()

    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 "save_roughness_raster"

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr("Save WEng roughness raster")

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr("WAsP scripts")

    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 "wasp_scripts"

    def shortHelpString(self):
        """
        Returns a localised short helper string for the algorithm. This string
        should provide a basic description about what the algorithm does and the
        parameters and outputs associated with it..
        """
        return self.tr(
            """Save roughness polygons as a WEng .grd file

            The layer should be of the type 'Polygon' and contain an attribute 'z0'. A path has to be specified where the file has to be saved.
            
            Note that the IEC 61400-12-1 standard specifies 50 m as a maximum horizontal grid spacing and it should be better (finer) than 70% of the hub height. The margin between turbine sites and map boundary should be around 25 hub heights.
            """
        )

    def initAlgorithm(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # We add the input vector features source. It can have any kind of
        # geometry.
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr("Input layer"),
                [QgsProcessing.TypeVectorPolygon],
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.VALUE,
                description=self.tr("Horizontal grid spacing (x/y) of the output raster"),
                type=QgsProcessingParameterNumber.Double,
                defaultValue=50.0,
                optional=False,
                minValue=20,
                maxValue=500,
            )
        )

        # We add a feature sink in which to store our processed features (this
        # usually takes the form of a newly created vector layer when the
        # algorithm is run in QGIS).
        # We add a file output of type CSV.
        self.addParameter(
            QgsProcessingParameterFileDestination(
                "mapfile",
                self.tr("Output File"),
                "WEng .grd File (*.grd)",
            )
        )

    def checkParameterValues(self, parameters, context):
        if parameters["mapfile"] == 'TEMPORARY_OUTPUT':
            return False, self.tr(f"You must choose a file path as Output File, WEng .grd files cannot be stored as a temporary file!")
        
        grid_spacing = self.parameterAsDouble(parameters, self.VALUE, context)
        layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        height_domain = layer.extent().height()
        width_domain = layer.extent().width()
        nr_cells_x = width_domain/grid_spacing
        nr_cells_y = height_domain/grid_spacing
        if nr_cells_x > 1000 or nr_cells_y > 1000:
            return False, self.tr(f"Your output raster map must have less than 1000x1000 pixels. This can be achieved by using a smaller area or using a coarser horizontal grid spacing.")

        return super().checkParameterValues(parameters, context)
    
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        if parameters["mapfile"] == 'TEMPORARY_OUTPUT':
            raise QgsProcessingException(
                "Cannot save to temporary file, please provide a full path of the file"
            )

        source = self.parameterAsSource(parameters, self.INPUT, context)
        
        # If source was not found, throw an exception to indicate that the algorithm
        # encountered a fatal error. The exception text can be any string, but in this
        # case we use the pre-built invalidSourceError method to return a standard
        # helper text for when a source cannot be evaluated
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT)
            )

        layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        
        if layer.crs().isGeographic():
            raise QgsProcessingException("WEng files cannot be saved in geographic coordinates! Reproject your layer to a metric coordinate system!")
       
        idx = layer.fields().indexFromName("z0")

        if idx == -1:
            raise QgsProcessingException(
                self.tr(
                    f"There is no valid roughness lines in this layer {layer.name()}! The layer must at least contain an attribute z0."
                )
            )
        
        dir = os.path.split(inspect.getfile(inspect.currentframe()))[0]
        feedback.pushInfo(dir)
        with open(os.path.join(dir,"EPSG-WAsP-LookUpTable.dat"), "r") as f:
            lines = f.read().splitlines()
        
        epsg_dic = {}
        for l in lines:
            name, code = l.split("|")
            epsg_dic[f"EPSG:{code.strip()}"] = name.strip()
        
        feedback.pushInfo(layer.crs().authid())
        map_epsg = layer.crs().authid()
        try:
            header = epsg_dic[map_epsg]
            feedback.pushInfo("EPSG found in map editor list")            
        except KeyError:
            feedback.pushInfo("EPSG not found in map editor list, please set it manually when opening in the map editor")

        grid_spacing = self.parameterAsDouble(parameters, self.VALUE, context)
        feedback.pushInfo("Running gdal:rasterize")
        raster_layer = processing.run("gdal:rasterize", {
            'INPUT':layer,
            'FIELD':'z0',
            'BURN':None,
            'USE_Z':False,
            'UNITS':1,
            'WIDTH':grid_spacing,
            'HEIGHT':grid_spacing,
            'EXTENT':layer.extent(),
            'NODATA':None,
            'OPTIONS':'',
            'DATA_TYPE':5,
            'INIT':None,
            'INVERT':False,
            'EXTRA':'',
            'OUTPUT':'TEMPORARY_OUTPUT'
            }
        )["OUTPUT"]
        
        feedback.pushInfo("Running gdal:translate")
        raster_output_file = processing.run("gdal:translate", {
            'INPUT':raster_layer,
            'TARGET_CRS':None,
            'NODATA':None,
            'COPY_SUBDATASETS':False,
            'OPTIONS':'',
            'EXTRA':'',
            'DATA_TYPE':0,
            'OUTPUT':parameters["mapfile"]
            }
        )["OUTPUT"]

        return {"OUTPUT":  raster_output_file}
