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

# QGIS
from qgis.core import (
    QgsProcessing,
    QgsProcessingException,
    QgsProcessingFeatureBasedAlgorithm,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterNumber,
    QgsProcessingParameters,
    QgsPropertyDefinition,
    QgsWkbTypes,
)
from qgis.PyQt.QtCore import QCoreApplication

# Projet
from qsfcgal.core.sfcgal_wrapper import (
    QgsGeometry_to_SFCGAL,
    SFCGAL_to_QgsGeometry,
    multipolygon_to_polygons,
)


class Extrude(QgsProcessingFeatureBasedAlgorithm):
    """
    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"
    EXTRUDE_X = "EXTRUDE_X"
    EXTRUDE_Y = "EXTRUDE_Y"
    EXTRUDE_Z = "EXTRUDE_Z"
    FORCE_SINGLEPART = "FORCE_SINGLEPART"

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

    def createInstance(self):
        return Extrude()

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

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

    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 outputName(self):
        return self.tr("extruded")

    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(
            "Extruding a polygon involves extending or prolonging the sides of a polygon in a "
            "specified direction, usually perpendicular to the plane of the polygon. This "
            "operation creates a new three-dimensional shape using the initial polygon as a base, "
            "and using x, y and z values to determine the dimensions and direction of the "
            "extrusion in three-dimensional space."
        )

    def inputLayerTypes(self):
        return [QgsProcessing.SourceType.TypeVectorPolygon]

    def outputWkbType(self, input_wkb_type):
        return QgsWkbTypes.Type.PolyhedralSurfaceZ

    def initParameters(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # extrude x parameter
        extrude_x_desc = self.tr("Extrude X")
        extrude_x_parameter = QgsProcessingParameterNumber(
            name=self.EXTRUDE_X,
            description=extrude_x_desc,
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=0,
        )
        extrude_x_parameter.setIsDynamic(True)
        extrude_x_parameter.setDynamicPropertyDefinition(
            QgsPropertyDefinition(
                self.EXTRUDE_X,
                extrude_x_desc,
                QgsPropertyDefinition.StandardPropertyTemplate.Double,
            )
        )
        extrude_x_parameter.setDynamicLayerParameterName(self.INPUT)
        self.addParameter(extrude_x_parameter)

        # extrude y parameter
        extrude_y_desc = self.tr("Extrude Y")
        extrude_y_parameter = QgsProcessingParameterNumber(
            name=self.EXTRUDE_Y,
            description=extrude_y_desc,
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=0,
        )
        extrude_y_parameter.setIsDynamic(True)
        extrude_y_parameter.setDynamicPropertyDefinition(
            QgsPropertyDefinition(
                self.EXTRUDE_Y,
                extrude_y_desc,
                QgsPropertyDefinition.StandardPropertyTemplate.Double,
            )
        )
        extrude_y_parameter.setDynamicLayerParameterName(self.INPUT)
        self.addParameter(extrude_y_parameter)

        # extrude z parameter
        extrude_z_desc = self.tr("Extrude Z")
        extrude_z_parameter = QgsProcessingParameterNumber(
            name=self.EXTRUDE_Z,
            description=extrude_z_desc,
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=1,
        )
        extrude_z_parameter.setIsDynamic(True)
        extrude_z_parameter.setDynamicPropertyDefinition(
            QgsPropertyDefinition(
                self.EXTRUDE_Z,
                extrude_z_desc,
                QgsPropertyDefinition.StandardPropertyTemplate.Double,
            )
        )
        extrude_z_parameter.setDynamicLayerParameterName(self.INPUT)
        self.addParameter(extrude_z_parameter)

        # Force single part parameter
        self.addParameter(
            QgsProcessingParameterBoolean(
                name=self.FORCE_SINGLEPART,
                description=self.tr(
                    "Forced explosion of MULTIPOLYGON into POLYGON if necessary for successful "
                    "treatment."
                ),
                defaultValue=True,
            )
        )

    def prepareAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)

        self.extrude_x = self.parameterAsDouble(parameters, self.EXTRUDE_X, context)
        self.extrude_x_dynamic = QgsProcessingParameters.isDynamic(
            parameters, self.EXTRUDE_X
        )
        if self.extrude_x_dynamic:
            self.extrude_x_prop = parameters[self.EXTRUDE_X]

        self.extrude_y = self.parameterAsDouble(parameters, self.EXTRUDE_Y, context)
        self.extrude_y_dynamic = QgsProcessingParameters.isDynamic(
            parameters, self.EXTRUDE_Y
        )
        if self.extrude_y_dynamic:
            self.extrude_y_prop = parameters[self.EXTRUDE_Y]

        self.extrude_z = self.parameterAsDouble(parameters, self.EXTRUDE_Z, context)
        self.extrude_z_dynamic = QgsProcessingParameters.isDynamic(
            parameters, self.EXTRUDE_Z
        )
        if self.extrude_z_dynamic:
            self.extrude_z_prop = parameters[self.EXTRUDE_Z]

        self.force_singlepart = self.parameterAsBoolean(
            parameters, self.FORCE_SINGLEPART, context
        )

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

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

    def processFeature(self, feature, context, feedback):
        if feedback.isCanceled():
            return []

        geom = feature.geometry()
        if geom is not None:
            extrude_x = self.extrude_x
            if self.extrude_x_dynamic:
                extrude_x, ok = self.extrude_x_prop.valueAsDouble(
                    context.expressionContext(), extrude_x
                )
                if not ok:
                    feedback.pushWarning("Ignoring feature with wrong X extrusion")
                    return []

            extrude_y = self.extrude_y
            if self.extrude_y_dynamic:
                extrude_y, ok = self.extrude_y_prop.valueAsDouble(
                    context.expressionContext(), extrude_y
                )
                if not ok:
                    feedback.pushWarning("Ignoring feature with wrong Y extrusion")
                    return []

            extrude_z = self.extrude_z
            if self.extrude_z_dynamic:
                extrude_z, ok = self.extrude_z_prop.valueAsDouble(
                    context.expressionContext(), extrude_z
                )
                if not ok:
                    feedback.pushWarning("Ignoring feature with wrong Y extrusion")
                    return []

            if geom.isMultipart() and self.force_singlepart:
                feedback.pushWarning(
                    f"Please note that the {feature.id()} entity is of the MULTIPOLYGON type. "
                    "Extrude only supports non-mulitpartite polygons, so this entity must be split "
                    "into several parts in order to run extrude."
                )
                polygons = multipolygon_to_polygons(geom)
                for elem in polygons:
                    geom_singlepart_sfcgal = QgsGeometry_to_SFCGAL(elem)
                    geom_sfcgal_singlepart_extrude = geom_singlepart_sfcgal.extrude(
                        extrude_x, extrude_y, extrude_z
                    )
                    result_sfcgal = (
                        geom_sfcgal_singlepart_extrude.to_polyhedralsurface()
                    )
                    geom_singlepart_qgis = SFCGAL_to_QgsGeometry(result_sfcgal)
                    feature.setGeometry(geom_singlepart_qgis)

            elif geom.isMultipart() and not self.force_singlepart:
                raise QgsProcessingException(
                    "You've chosen not to force single-part geometries, but your geometries are "
                    "mulitpolygon. Processing cannot be performed. Extrude does not (yet) support "
                    "multipolygon."
                )

            else:
                geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                geom_sfcgal_extrude = geom_sfcgal.extrude(
                    extrude_x, extrude_y, extrude_z
                )
                geom_sfcgal_extrude = geom_sfcgal_extrude.to_polyhedralsurface()
                geom_qgis_extrude = SFCGAL_to_QgsGeometry(geom_sfcgal_extrude)
                feature.setGeometry(geom_qgis_extrude)

        else:
            feedback.pushInfo(
                f"Entity {feature.id()} not added to the result layer because its input geometry "
                "is null."
            )

        return [feature]
