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

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

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

# Geom
POINT = QgsWkbTypes.Type.Point
MULTIPOINT = QgsWkbTypes.Type.MultiPoint
LINESTRING = QgsWkbTypes.Type.LineString
MULTILINESTRING = QgsWkbTypes.Type.MultiLineString
POLYGON = QgsWkbTypes.Type.Polygon
MULTIPOLYGON = QgsWkbTypes.Type.MultiPolygon


class Minkowski_sum(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_A = "INPUT_A"
    INPUT_B = "INPUT_B"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return Minkowski_sum()

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

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

    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 function performs a 2D minkowski sum of a point, line or polygon with a polygon. "
            "A minkowski sum of two geometries A and B is the set of all points that are the sum "
            "of any point in A and B."
        )

    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_A,
                description=self.tr("Input A"),
                types=[QgsProcessing.SourceType.TypeVector],
            )
        )

        self.addParameter(
            QgsProcessingParameterFeatureSource(
                name=self.INPUT_B,
                description=self.tr("Input B"),
                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("Minkowski_sum"),
                type=QgsProcessing.SourceType.TypeVectorPolygon,
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        input_a = self.parameterAsSource(parameters, self.INPUT_A, context)
        input_b = self.parameterAsSource(parameters, self.INPUT_B, context)

        if input_a is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT_A)
            )

        if input_b is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT_B)
            )

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

        feedback.pushInfo("CRS is {}".format(input_a.sourceCrs().authid()))
        total = 100.0 / input_a.featureCount() if input_a.featureCount() else 0

        features_A = input_a.getFeatures()
        features_B = input_b.getFeatures()

        if input_b.wkbType() != QgsWkbTypes.Type.Polygon:
            feedback.reportError(
                "Impossible to run processing : the second argument must be a Polygon"
                f" and not {QgsWkbTypes.displayString(input_b.wkbType())}"
            )
            return {}

        for current, feature_A in enumerate(features_A):
            if feedback.isCanceled():
                break

            geom_A = QgsGeometry_to_SFCGAL(feature_A.geometry())

            if geom_A:
                for index, feature_B in enumerate(features_B):
                    geom_B = QgsGeometry_to_SFCGAL(feature_B.geometry())
                    if geom_B:
                        result_geom = geom_A.minkowski_sum(geom_B)
                        new_geom = SFCGAL_to_QgsGeometry(result_geom)
                        feature_A.setGeometry(new_geom)
                        sink.addFeature(feature_A, QgsFeatureSink.Flag.FastInsert)

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

        return {self.OUTPUT: dest_id}
