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

# QGIS
from qgis.core import (
    Qgis,
    QgsFeature,
    QgsFeatureRequest,
    QgsFeatureSink,
    QgsProcessing,
    QgsProcessingAlgorithm,
    QgsProcessingException,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterFeatureSink,
    QgsProcessingParameterFeatureSource,
)
from qgis.PyQt.QtCore import QCoreApplication

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


class Intersection_3D(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"
    FORCE_SOLID = "FORCE_SOLID"

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

    def createInstance(self):
        return Intersection_3D()

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

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

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr("3D")

    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 "3d"

    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(
            "The algorithm identifies the common spatial 3D elements shared by two or more layers. "
            "An intersection represents the portion where features from different layers overlap."
            "The algorithm analyzes the geometric relationships, such as polygons 3D "
            "within the input layers to precisely determine these intersecting areas. "
            "The output is a new layer or dataset highlighting the spatial overlap."
            ""
            ""
            "Warning: due to an error in QGIS's handling of 3D data, if you run processing with "
            "temporary output, you'll get an error or empty geometry output. You must specify an "
            "output to a GeoPackage."
            ""
            "MultiPolygonZ geometries are considered by QgsProcessing as invalid geometries. "
            "The 'Invalid feature filtering' parameter must therefore be set to 'Do not Filter'."
        )

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

        self.addParameter(
            QgsProcessingParameterBoolean(
                name=self.FORCE_SOLID,
                description=self.tr(
                    "Convert PolyhedralSurface to Solid for intersection"
                ),
                defaultValue=True,
            )
        )

        # 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("Intersection 3D"),
                type=QgsProcessing.SourceType.TypeVector,
            )
        )

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

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

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

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

        # WARNING
        # Processing considers a Polyhedral to be an invalid geometry.
        # QgsFeatureRequest(), Qgis.ProcessingFeatureSourceFlag.SkipGeometryValidityChecks :
        # Is a work around that should be removed once the bug has been fixed in QGIS.
        # TODO: drop this workaround
        features_source = source.getFeatures(
            QgsFeatureRequest(),
            Qgis.ProcessingFeatureSourceFlag.SkipGeometryValidityChecks,
        )
        features_overlay = overlay.getFeatures(
            QgsFeatureRequest(),
            Qgis.ProcessingFeatureSourceFlag.SkipGeometryValidityChecks,
        )

        result_feature = []

        # Source
        list_feature_source = []
        for current, feature_source in enumerate(features_source):
            list_feature_source.append(feature_source)

        list_feature_overlay = []
        for current_overlay, feature_overlay in enumerate(features_overlay):
            list_feature_overlay.append(feature_overlay)

        for feature_source in list_feature_source:
            if feedback.isCanceled():
                break

            geom_source = feature_source.geometry()
            if geom_source.isNull():
                feedback.pushInfo(
                    f"Entity {feature_source.id()} not added to the result layer because its input "
                    "geometry is null."
                )
                continue

            geom_source_sfcgal = QgsGeometry_to_SFCGAL(geom_source)
            if force_solid and source.wkbType() == 1015:
                geom_source_sfcgal = geom_source_sfcgal.to_solid()

            # Overlay
            for feature_overlay in list_feature_overlay:
                if feedback.isCanceled():
                    break

                geom_overlay = feature_overlay.geometry()
                if not geom_overlay:
                    continue
                print(geom_source_sfcgal)
                geom_overlay_sfcgal = QgsGeometry_to_SFCGAL(geom_overlay)
                # Force solid
                if force_solid and overlay.wkbType() == 1015:
                    geom_overlay_sfcgal = geom_overlay_sfcgal.to_solid()
                # 3D Intersection
                test_intersection = geom_source_sfcgal.intersects_3d(
                    geom_overlay_sfcgal
                )
                if not test_intersection:
                    continue

                result = geom_source_sfcgal.intersection_3d(geom_overlay_sfcgal)
                # QGIS not supported SOLID, so we convert result to POLYHEDRAL
                if result.geom_type == "SOLID":
                    result = result.to_polyhedralsurface()
                # Convert geom result to QgsGeometry
                new_geom = SFCGAL_to_QgsGeometry(result)
                new_feature = QgsFeature(feature_source)
                new_feature.setGeometry(new_geom)
                result_feature.append(new_feature)

        if len(result_feature) > 0:
            wkb_type_output = result_feature[0].geometry().wkbType()

            (sink, dest_id) = self.parameterAsSink(
                parameters=parameters,
                name=self.OUTPUT,
                context=context,
                fields=source.fields(),
                geometryType=wkb_type_output,
                crs=source.sourceCrs(),
            )
            for feature in result_feature:
                sink.addFeature(feature, QgsFeatureSink.Flag.FastInsert)
        else:
            feedback.pushInfo(
                "The result of the intersection is null, as no entity in the source layer "
                "intersects an entity in the overlay layer."
            )

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

        return {self.OUTPUT: dest_id}
