# SPDX-License-Identifier: GPL-2.0-or-later

# QGIS
from qgis.core import (
    QgsFeatureSink,
    QgsGeometry,
    QgsProcessing,
    QgsProcessingAlgorithm,
    QgsProcessingException,
    QgsProcessingParameterFeatureSink,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterNumber,
    QgsWkbTypes,
)
from qgis.PyQt.QtCore import QCoreApplication

# Projet
from qsfcgal.core.sfcgal_wrapper import QgsGeometry_to_SFCGAL, SFCGAL_to_QgsGeometry


class LineSubString(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.

    INPUT = "INPUT"
    START = "START"
    END = "END"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return LineSubString()

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

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr("Line sub string")

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

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

    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(
            "Computes the line which is the section of the input line starting and ending at the "
            "given fractional locations. The first argument must be a LINESTRING. The second and "
            "third arguments are values in the range [0, 1] representing the start and end "
            "locations as fractions of line length. The Z and M values are interpolated for added "
            "endpoints if present."
        )

    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(
                name=self.INPUT,
                description=self.tr("Input layer"),
                types=[QgsProcessing.SourceType.TypeVectorLine],
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.START,
                description=self.tr("Start"),
                type=QgsProcessingParameterNumber.Type.Double,
                defaultValue=0.1,
                maxValue=1,
                minValue=0,
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.END,
                description=self.tr("End"),
                type=QgsProcessingParameterNumber.Type.Double,
                defaultValue=0.9,
                maxValue=1,
                minValue=0,
            )
        )

        # 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).
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr("Line sub string"),
                type=QgsProcessing.SourceType.TypeVectorLine,
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        start = self.parameterAsDouble(parameters, self.START, context)
        end = self.parameterAsDouble(parameters, self.END, context)

        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT)
            )

        (sink, dest_id) = self.parameterAsSink(
            parameters=parameters,
            name=self.OUTPUT,
            context=context,
            fields=source.fields(),
            geometryType=QgsWkbTypes.Type.MultiLineString,
            crs=source.sourceCrs(),
        )

        if start > end:
            raise QgsProcessingException(
                feedback.reportError(
                    self.tr(
                        "Error : Start value between 0 and 1 must be strictly less than the end "
                        "value."
                    )
                )
            )

        feedback.pushInfo("CRS is {}".format(source.sourceCrs().authid()))

        total = 100.0 / source.featureCount() if source.featureCount() else 0
        features = source.getFeatures()

        for current, feature in enumerate(features):
            if feedback.isCanceled():
                break

            geom = feature.geometry()

            if geom is not None:
                try:
                    if geom.isMultipart():
                        result_lines = []
                        line = geom.asGeometryCollection()
                        line_strings = [
                            geom
                            for geom in line
                            if geom.type() == QgsWkbTypes.GeometryType.LineGeometry
                        ]
                        for i, line in enumerate(line_strings):
                            geom_sfcgal = QgsGeometry_to_SFCGAL(line)
                            result_geom = geom_sfcgal.line_sub_string(start, end)
                            line_result = SFCGAL_to_QgsGeometry(result_geom)
                            result_lines.append(line_result)
                            new_geom = QgsGeometry()
                            for line_string in result_lines:
                                if new_geom.isEmpty():
                                    new_geom = line_string
                                else:
                                    new_geom = new_geom.combine(line_string)

                    else:
                        geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                        result_geom = geom_sfcgal.line_sub_string(start, end)
                        new_geom = SFCGAL_to_QgsGeometry(result_geom)

                except TypeError:
                    feedback.pushInfo(
                        f"Error with the entity {feature.id()}, it will be added to the result but "
                        "without line sub set."
                    )
                    new_geom = QgsGeometry()
                feature.setGeometry(new_geom)
                sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)

                # Update the progress bar
                feedback.setProgress(int(current * total))
            else:
                sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)
                feedback.pushInfo(
                    f"Entity {feature.id()} added to the result layer but without line sub set "
                    "because its input geometry is null."
                )

        return {self.OUTPUT: dest_id}
