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

# QGIS
from qgis.core import (
    QgsFeatureSink,
    QgsGeometry,
    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,
    sfcgal,
)

# 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 Difference(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"
    OVERLAY = "OVERLAY"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return Difference()

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

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

    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(
            "Returns the geometric difference between two layers, an input layer and a mask layer. "
            "More concretely, this returns the part of the input geometry that doesn't intersect a "
            "part of the mask layer geometry."
        )

    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(
            QgsProcessingParameterFeatureSource(
                name=self.OVERLAY,
                description=self.tr("Overlay layer"),
                types=[QgsProcessing.SourceType.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).
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr("Difference"),
                type=QgsProcessing.SourceType.TypeVector,
            )
        )

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

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

        if overlay is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.OVERLAY)
            )

        g1 = source.wkbType()
        go = QgsWkbTypes.Type.Unknown

        """
        INPUT ↓
        |            | Point | Linestring | Polygon |   ← OVERLAY
        |---------   |-------|-----------|----------|
        | Point      |   1   |      2    |    3     |
        | Linestring |   4   |      5    |    6     |
        | Polygon    |   7   |      8    |    9     |
        """
        # 1, 2, 3
        if g1 == POINT or g1 == MULTIPOINT:
            go = POINT

        # 4, 5, 6
        if g1 == LINESTRING or g1 == MULTILINESTRING:
            go = MULTILINESTRING

        # 7, 8, 9
        if g1 == POLYGON or g1 == MULTIPOLYGON:
            go = MULTIPOLYGON

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

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

        features_source = source.getFeatures()
        features_overlay = list(overlay.getFeatures())

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

            geom = feature.geometry()
            collection = sfcgal.GeometryCollection()
            geom_overlay = None

            if geom is not None:
                geom_input = QgsGeometry_to_SFCGAL(geom)

                # Checks which overlay geometries the current input geometry interesects
                for current_overlay, feature_overlay in enumerate(features_overlay):
                    geom_overlay = QgsGeometry_to_SFCGAL(feature_overlay.geometry())
                    if geom_input.intersects(geom_overlay):
                        collection.addGeometry(geom_overlay)

                if len(collection) > 0:
                    result_geom = geom_input.difference(collection)

                    if result_geom.to_wkt() == "GEOMETRYCOLLECTION EMPTY":
                        new_geom = QgsGeometry().fromWkt(
                            f"{QgsWkbTypes.displayString(go).upper()} EMPTY"
                        )

                    else:
                        new_geom = SFCGAL_to_QgsGeometry(result_geom)

                # if input geometry no intersects any overlay geometry : return input geometry
                else:
                    new_geom = feature.geometry()

                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)
                f"Entity {feature.id()} added to the result layer but without a difference because "
                "its input geometry is null."

        return {self.OUTPUT: dest_id}
