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

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

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


class Translate(QgsProcessingAlgorithm):
    INPUT = "INPUT"
    OUTPUT = "OUTPUT"
    TRANSLATE_X = "TRANSLATE_X"
    TRANSLATE_Y = "TRANSLATE_Y"
    TRANSLATE_Z = "TRANSLATE_Z"

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

    def createInstance(self):
        return Translate()

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

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

    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(
            "This algorithm translates a vector layer by a specified distance along the X and Y "
            "axes. It takes a vector layer and two translation values (X, Y) as inputs. The "
            "algorithm applies the translation to each vertex or feature in the layer, shifting "
            "their positions by the given values along the X and Y directions. The output is a "
            "new vector layer with updated coordinates."
        )

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

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.TRANSLATE_X,
                description=self.tr("Translate X"),
                type=QgsProcessingParameterNumber.Type.Double,
                defaultValue=0,
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.TRANSLATE_Y,
                description=self.tr("Translate Y"),
                type=QgsProcessingParameterNumber.Type.Double,
                defaultValue=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("Translate"),
                type=QgsProcessing.SourceType.TypeVectorPolygon,
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)

        translate_x = self.parameterAsDouble(parameters, self.TRANSLATE_X, context)
        translate_y = self.parameterAsDouble(parameters, self.TRANSLATE_Y, context)

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

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

        features = source.getFeatures()
        list_result_features = []
        for current, feature in enumerate(features):
            if feedback.isCanceled():
                break

            geom = feature.geometry()

            if geom is not None:
                geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                geom_sfcgal_translate = geom_sfcgal.translate_2d(
                    translate_x, translate_y
                )
                geom_qgis_translate = SFCGAL_to_QgsGeometry(geom_sfcgal_translate)
                output_wkbtype = geom_qgis_translate.wkbType()
                feature.setGeometry(geom_qgis_translate)
                list_result_features.append(feature)
            else:
                feedback.pushInfo(
                    f"Entity {feature.id()} not added to the result layer because its input "
                    "geometry is null."
                )

        (sink, dest_id) = self.parameterAsSink(
            parameters=parameters,
            name=self.OUTPUT,
            context=context,
            fields=source.fields(),
            geometryType=output_wkbtype,
            crs=source.sourceCrs(),
        )
        for feature in list_result_features:
            sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)

        return {self.OUTPUT: dest_id}
