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

"""
***************************************************************************
*                                                                         *
*   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.                                   *
*                                                                         *
***************************************************************************
"""

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

VECTORMAP_ELEV_COL = "elev"
VECTORMAP_ID_COLS = ["id_left", "id_right"]
VECTORMAP_IDL_COL, VECTORMAP_IDR_COL = VECTORMAP_ID_COLS


class SaveLandcoverGML(QgsProcessingAlgorithm):
    """
    This is an algorithm that saves a map with vector lines and
    saves it as a WAsP .gml 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"
    TABLE = "TABLE"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return SaveLandcoverGML()

    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_gml_landcover_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 landcover 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 landcover lines as a WAsP .gml file

            The layer should be of the type 'LineString' and contain attributes 'id_right' and 'id_left' which represent the id right and left of that contour line. The second input is the lookup table that has column 'id' which ties a roughness length (z0) and displacement height (d) to each landcover ID (id) of the land cover lines. 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],
            )
        )

        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.TABLE,
                self.tr("Input landcover table"),
                [QgsProcessing.TypeVector],
            )
        )

        # 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 GML File (*.gml)"
            )
        )

    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 .gml 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)
        layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        layer = processing.run(
            "native:multiparttosingleparts",
            {"INPUT": layer, "OUTPUT": "TEMPORARY_OUTPUT"},
            context=context,
            feedback=feedback,
        )["OUTPUT"]
        table = self.parameterAsVectorLayer(parameters, self.TABLE, context)
        lctable = {}
        features = table.getFeatures()
        for i, feat in enumerate(features):
            try:
                lcid = int(feat["id"])
            except:                
                lcid = int(feat["index"])
                feedback.pushWarning("The landcover ID's should be called 'id' but was called 'index', using this word for landcover IDs is deprecated.")
            lctable[lcid] = {
                "z0": feat["z0"],
                "d": feat["d"],
                "desc": feat["desc"],
            }
        # 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)
            )
        feedback.pushInfo("Number of features to convert: " + parameters["mapfile"])

        # Create maping of namespaces
        props = []

        epsgc = layer.crs().authid().replace("EPSG:","")
        max_ext = layer.extent()
        idx1 = layer.fields().indexFromName("id_left")
        idx2 = layer.fields().indexFromName("id_right")
        with open(parameters["mapfile"], "w", newline="\r\n") as fobj:
            # top level container for map
            wvmap = f'<map:WaspVectorMap xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:map="http://www.wasp.dk/schemas/WaspVectorMap/1.0" xmlns:wasp-chg="http://www.wasp.dk/schemas/WaspChangeLines/1.0" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" gml:id="WaspVectorMap.0" xsi:schemaLocation="http://www.wasp.dk/schemas/ http://ogr.maptools.org/ WaspVectorMap.xsd">'
            fobj.write(wvmap + "\n")

            # create description and map extents
            fobj.write("<map:Description>" + parameters["mapfile"] + "</map:Description>" + "\n")
            fobj.write('<map:CreatedBy software="WAsP Map Editor" version="12.04.04.64"/>' + "\n")
            fobj.write(f"""<map:MaxExtents>
    <gml:Envelope srsName="urn:ogc:def:crs:EPSG::{epsgc}">
    <gml:lowerCorner>{max_ext.xMinimum()} {max_ext.yMinimum()}</gml:lowerCorner>
    <gml:upperCorner>{max_ext.xMaximum()} {max_ext.yMaximum()}</gml:upperCorner>
    </gml:Envelope>
</map:MaxExtents>""" + "\n"
            )

            # loop over landcover lines and write to file
            features = layer.getFeatures()
            feature_strs = []
            for fid, feat in enumerate(features):
                id_left = int(feat.attributes()[idx1])
                id_right = int(feat.attributes()[idx2])
                if id_left not in props:
                    props.append(id_left)
                if id_right not in props:
                    props.append(id_right)
                line = feat.geometry().asPolyline()
                pts = [(p.x(), p.y()) for p in line]
                fmt_line = """<map:LandCoverMapMember>
    <wasp-chg:ChangeLine gml:id="line.{id}">
        <wasp-chg:geometry>
            <gml:LineString srsName="urn:ogc:def:crs:EPSG::{epsg}" gml:id="line.{id}.geom">
                <gml:posList>{pos_list}</gml:posList>
            </gml:LineString>
        </wasp-chg:geometry>
        <wasp-chg:id_left xlink:href="#sfp.{id_left}"/>
        <wasp-chg:id_right xlink:href="#sfp.{id_right}"/>
    </wasp-chg:ChangeLine>
</map:LandCoverMapMember>"""
                pos_list = " ".join([f"{i[0]:.1f} {i[1]:.1f}" for i in pts])
                fmt_line = fmt_line.format(
                    id=int(fid),
                    id_left=int(id_left),
                    id_right=int(id_right),
                    epsg=epsgc,
                    pos_list=pos_list,
                )
                feature_strs.append(fmt_line)

            # open landcover table tag
            fobj.write('<wasp-chg:SurfacePropertiesTable gml:id="sfpt.0">'+ "\n")


            # loop through items in land cover table
            for key in props:
                if lctable[key]["z0"] <= 0:
                    lct = "Water_Surface"
                    z0status, dstatus = "Fixed","Fixed"
                elif lctable[key]["z0"] > 0 and lctable[key]["d"] > 0:
                    lct = "Roughness_and_Displacement"
                    z0status, dstatus = "Configurable","Configurable"
                else:
                    lct = "Land_Roughness"
                    z0status, dstatus = "Configurable","Fixed"
                fmt_disp = """
                    <wasp-chg:LandCoverParameter wasp-chg:ParamID="d" wasp-chg:ParamUnit="m" wasp-chg:ParamType="{dstatus}">
                        <wasp-chg:ZeroPlaneDisplacementHeight>{d}</wasp-chg:ZeroPlaneDisplacementHeight>
                    </wasp-chg:LandCoverParameter>"""
                fmt_z0 = """
                    <wasp-chg:LandCoverParameter wasp-chg:ParamID="Z0" wasp-chg:ParamUnit="m" wasp-chg:ParamType="{z0status}">
                        <wasp-chg:AerodynamicalRoughnessLength>{z0}</wasp-chg:AerodynamicalRoughnessLength>
                    </wasp-chg:LandCoverParameter>"""
                param_str = fmt_z0.format(z0=lctable[key]["z0"] , z0status=z0status)
                param_str += fmt_disp.format(d=lctable[key]["d"] , dstatus=dstatus)
                # format for entry in landcover table
                fmt_table = """ <wasp-chg:SurfacePropertiesTableMember>
        <wasp-chg:SurfaceProperties gml:id="sfp.{id}">
            <wasp-chg:LandCover wasp-chg:LandCoverType="{lct}">
                <wasp-chg:LandCoverParameters>{parameters}
                </wasp-chg:LandCoverParameters>
            </wasp-chg:LandCover>
        </wasp-chg:SurfaceProperties>
    </wasp-chg:SurfacePropertiesTableMember>"""
                fmt_table = fmt_table.format(id=int(key), lct=lct, parameters=param_str)
                fobj.write(fmt_table + "\n")

            # close land cover table tag
            fobj.write('</wasp-chg:SurfacePropertiesTable>'+ "\n")
        
            for f in feature_strs:
                fobj.write(f + "\n")
                        
            fobj.write("</map:WaspVectorMap>" + "\n")
            
        return {self.OUTPUT: layer.id()}
