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

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

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


class Force_LHR(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"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return Force_LHR()

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

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

    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(
            "Forces the orientation of the vertices in a polygon to follow a Left-Hand-Rule, in "
            "which the area that is bounded by the polygon is to the left of the boundary. In "
            "particular, the exterior ring is orientated in a clockwise direction and the interior "
            "rings in a counter-clockwise direction."
        )

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

        # 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("Force_LHR"),
                type=QgsProcessing.SourceType.TypeVectorPolygon,
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, 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=source.wkbType(),
            crs=source.sourceCrs(),
        )

        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:
                geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                result_geom = geom_sfcgal.force_lhr()
                new_geom = SFCGAL_to_QgsGeometry(result_geom)
                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 a force_lhr "
                    "because its input geometry is null."
                )

        return {self.OUTPUT: dest_id}
