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

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

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


class OptimalAlphaShapes(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"
    ALLOW_HOLES = "ALLOW_HOLES"
    NB_COMPONENTS = "NB_COMPONENTS"
    OUTPUT = "OUTPUT"

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

    def createInstance(self):
        return OptimalAlphaShapes()

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

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

    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 optimal alpha-shape of the points in a geometry. The alpha-shape is "
            "computed using a value of α chosen so that: "
            "  - the number of polygon elements is equal to or smaller than nb_components "
            "(which defaults to 1)"
            "  - all input points are contained in the shape"
            "The result will not contain holes unless the optional allow_holes argument is "
            "specified as true."
        )

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

        self.addParameter(
            QgsProcessingParameterBoolean(
                name=self.ALLOW_HOLES, description=self.tr("Allow holes")
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                name=self.NB_COMPONENTS,
                description=self.tr("Nb components"),
                type=QgsProcessingParameterNumber.Type.Integer,
                defaultValue=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("Optimal alpha shapes"),
                type=QgsProcessing.SourceType.TypeVectorPolygon,
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        nb_components = self.parameterAsDouble(parameters, self.NB_COMPONENTS, context)
        allow_holes = self.parameterAsBoolean(parameters, self.ALLOW_HOLES, 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.Polygon,
            crs=source.sourceCrs(),
        )

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

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

        # In the case of a point-type layer, all points are grouped together in a MultiPoint.
        # Then we apply the algorithm to this mulitpoint.
        if source.wkbType() == QgsWkbTypes.Type.Point:
            multi_point = QgsGeometry()
            for current, feature in enumerate(features):
                if feedback.isCanceled():
                    break

                geom = feature.geometry()
                if geom is not None:
                    if geom.type() == QgsWkbTypes.GeometryType.PointGeometry:
                        if multi_point.isEmpty():
                            multi_point = geom
                        else:
                            multi_point = multi_point.combine(geom)
                feedback.setProgress(int(current * total))

            geom_sfcgal = QgsGeometry_to_SFCGAL(multi_point)
            result_geom = geom_sfcgal.optimal_alpha_shapes(
                allow_holes, int(nb_components)
            )
            new_geom = SFCGAL_to_QgsGeometry(result_geom)
            feature.setGeometry(new_geom)
            sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)

        # In the case of a MultiPoint layer, processing is iterated on each MultiPoint.
        if source.wkbType() == QgsWkbTypes.Type.MultiPoint:
            for current, feature in enumerate(features):
                if feedback.isCanceled():
                    break

                geom = feature.geometry()

                if geom is not None:
                    try:
                        geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                        result_geom = geom_sfcgal.optimal_alpha_shapes(
                            allow_holes, int(nb_components)
                        )
                        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 alpha shapes polygon."
                        )
                        new_geom = QgsGeometry()
                    feature.setGeometry(new_geom)
                    sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)

                    # Update the progress bar
                    feedback.setProgress(int(current * total))

        return {self.OUTPUT: dest_id}
