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

# QGIS
from qgis.core import (
    QgsFeature,
    QgsFeatureSink,
    QgsFields,
    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


class Convexhull(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 Convexhull()

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

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

    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(
            "A convex hull is the smallest convex shape that encloses a given set of "
            "points in space. It's like the tightest rubber band stretched around a set "
            "of points, forming the smallest convex polygon or polyhedron that contains "
            "all the points."
        )

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

        # 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("Convexhull"),
                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)
            )

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

        features = source.getFeatures()
        points = []

        if source.featureCount() == 0:
            feedback.pushInfo(
                "The layer has no entities, it is not possible to calculate a convexhull. "
                "No result layer."
            )
            feedback.cancel()

        for current, feature in enumerate(features):
            if feedback.isCanceled():
                break
            try:
                geom = feature.geometry()

                if geom.wkbType() == QgsWkbTypes.Type.Point:
                    points.append(geom.asPoint())

                if geom.wkbType() == QgsWkbTypes.Type.MultiPoint:
                    for point in geom.asMultiPoint():
                        points.append(point)
            except Exception as e:
                feedback.pushInfo(f"Error {e} please check entity {feature.id}")

        global_multipoint = QgsGeometry.fromMultiPointXY(points)
        nb_point = len(points)
        geom_sfcgal = QgsGeometry_to_SFCGAL(global_multipoint)

        try:
            result_geom = geom_sfcgal.convexhull()
        except Exception as e:
            feedback.pushInfo(f"Error during execution of convexhull : {e}")

        new_geom = SFCGAL_to_QgsGeometry(result_geom)

        if nb_point == 1:
            output_geom_type = QgsWkbTypes.Type.Point

        elif nb_point == 2:
            output_geom_type = QgsWkbTypes.Type.LineString

        elif nb_point > 2:
            output_geom_type = QgsWkbTypes.Type.Polygon

        else:
            output_geom_type = QgsWkbTypes.Type.Unknown

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

        try:
            result_feature = QgsFeature()
            result_feature.setGeometry(new_geom)
            sink.addFeature(result_feature, QgsFeatureSink.Flag.FastInsert)
        except Exception as e:
            feedback.pushInfo(f"Error when loading the resulting layer : {e}")

        return {self.OUTPUT: dest_id}
