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

"""
Save contour lines with a left and right roughness length 'z0' 
to a .map file. The elevation lines must be
LineStrings and have the attributes 'z0_left' and 'z0_right'
"""

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


class SaveRoughnessMap(QgsProcessingAlgorithm):
    """
    This scripts saves roughness contours as a WAsP .map 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"

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

    def createInstance(self):
        return SaveRoughnessMap()

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

    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 WAsP roughness lines")

    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-change lines as a WAsP .map file

            The layer should be of the type 'LineString' and contain attributes 'z0_right' and 'z0_left' which represent the roughness length right and left of that contour line. A path has to be specified where the file has to be saved."""
        )

    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.TypeVectorLine],
            )
        )

        # 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"),
                "WAsP map File (*.map)",
            )
        )

    def checkParameterValues(self, parameters, context):
        if parameters["mapfile"] == 'TEMPORARY_OUTPUT':
            return False, self.tr(f"You must choose a file path as Output File, WAsP .map files cannot be stored as a temporary file!")

        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"
            )
        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        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("WAsP files cannot be saved in geographic coordinates! Reproject your layer to a metric coordinate system!")

        layer = processing.run(
            "native:multiparttosingleparts",
            {"INPUT": layer, "OUTPUT": "TEMPORARY_OUTPUT"},
            context=context,
            feedback=feedback,
        )["OUTPUT"]
        features = layer.getFeatures()
        nfeatures = layer.featureCount()
        feedback.pushInfo("Number of features to convert: " + str(layer.featureCount()))
        
        idx1 = layer.fields().indexFromName("z0_left")
        idx2 = layer.fields().indexFromName("z0_right")

        if idx1 == -1 or idx2 == -1:
            raise QgsProcessingException(
                self.tr(
                    f"There is no valid roughness lines in this layer {layer.name()}! The layer must at least contain the columns z0_left and z0_right."
                )
            )
        
        dir = os.path.split(inspect.getfile(inspect.currentframe()))[0]
        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.pushWarning("EPSG not found in map editor list, please set it manually when opening in the map editor! WAsP will not be able to geolocate this layer.")
            header = ""

        with open(parameters["mapfile"], "w", newline="\r\n") as fobj:
            fobj.write("+ QGIS map | " + header + " | WME ver. 12.4.11.77" + "\n")

            # Fixed point #1 in user and metric [m] coordinates:
            # X1_user, Y1_user, X1_metric, Y1_metric
            fobj.write("%3.1f %3.1f %3.1f %3.1f\n" % (0.0, 0.0, 0.0, 0.0))

            # Fixed point #2 in user and metric [m] coordinates:
            # X2_user, Y2_user, X2_metric, Y2_metric
            fobj.write("%3.1f %3.1f %3.1f %3.1f\n" % (1.0, 0.0, 1.0, 0.0))

            # Scaling factor and offset for height scale (z),
            # Zmetric = scaling factor X (zuser +offset)
            fobj.write("%3.1f %15.1f\n" % (1.0, 0.0))

            for current, feat in enumerate(features):
                # geom = ogr.CreateGeometryFromWkt(feat.geometry().asWkt())
                # geom.SetCoordinateDimension(2)
                line = feat.geometry().asPolyline()
                pts = [(p.x(), p.y()) for p in line]
                n_pts = len(pts)
                z0_left = feat.attributes()[idx1]
                z0_right = feat.attributes()[idx2]
                fobj.write(f"{z0_left:10.4f} {z0_right:10.4f} {n_pts:10d}\n")
                xy_string = " ".join(f"{x:10.1f} {y:10.1f}" for x, y in pts)
                fobj.write(xy_string + "\n")
                feedback.setProgress(int(current/nfeatures))
                

        return {"OUTPUT": layer.id()}
