# 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 ExtrudePolygonStraightSkeleton(QgsProcessingFeatureBasedAlgorithm):
    """
    Extrude a polygon along its straight skeleton with specified building and roof heights.

    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"
    BUILDING_HEIGHT = "BUILDING_HEIGHT"
    ROOF_HEIGHT = "ROOF_HEIGHT"
    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 ExtrudePolygonStraightSkeleton()

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

    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 polygon straight skeleton")

    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("extrude polygon straight skeleton")

    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(
            "Extrude a polygon along its straight skeleton with specified building and roof "
            "heights."
        )

    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.
        """
        building_height_desc = self.tr("Building height")
        building_height_parameter = QgsProcessingParameterNumber(
            name=self.BUILDING_HEIGHT,
            description=building_height_desc,
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=0,
        )
        building_height_parameter.setIsDynamic(True)
        building_height_parameter.setDynamicPropertyDefinition(
            QgsPropertyDefinition(
                self.BUILDING_HEIGHT,
                building_height_desc,
                QgsPropertyDefinition.StandardPropertyTemplate.Double,
            )
        )
        building_height_parameter.setDynamicLayerParameterName(self.INPUT)
        self.addParameter(building_height_parameter)

        roof_height_desc = self.tr("Roof height")
        roof_height_parameter = QgsProcessingParameterNumber(
            name=self.ROOF_HEIGHT,
            description=roof_height_desc,
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=0,
        )
        roof_height_parameter.setIsDynamic(True)
        roof_height_parameter.setDynamicPropertyDefinition(
            QgsPropertyDefinition(
                self.ROOF_HEIGHT,
                roof_height_desc,
                QgsPropertyDefinition.StandardPropertyTemplate.Double,
            )
        )
        roof_height_parameter.setDynamicLayerParameterName(self.INPUT)
        self.addParameter(roof_height_parameter)

        self.addParameter(
            QgsProcessingParameterBoolean(
                name=self.FORCE_SINGLEPART,
                description=self.tr(
                    "Forced explosion of MULTIPOLYGON into POLYGON if necessary for successful "
                    "treatment. This processing does not handle multipolygon inputs."
                ),
                defaultValue=True,
            )
        )

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

        self.building_height = self.parameterAsDouble(
            parameters, self.BUILDING_HEIGHT, context
        )
        self.building_height_dynamic = QgsProcessingParameters.isDynamic(
            parameters, self.BUILDING_HEIGHT
        )
        if self.building_height_dynamic:
            self.building_height_prop = parameters[self.BUILDING_HEIGHT]

        self.roof_height = self.parameterAsDouble(parameters, self.ROOF_HEIGHT, context)
        self.roof_height_dynamic = QgsProcessingParameters.isDynamic(
            parameters, self.ROOF_HEIGHT
        )
        if self.roof_height_dynamic:
            self.roof_height_prop = parameters[self.ROOF_HEIGHT]

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

        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:
            building_height_parameter = self.building_height
            if self.building_height_dynamic:
                building_height_parameter, ok = self.building_height_prop.valueAsDouble(
                    context.expressionContext(), building_height_parameter
                )
                if not ok:
                    feedback.pushWarning("Ignoring feature with wrong building height")
                    return []

            roof_height_parameter = self.roof_height
            if self.roof_height_dynamic:
                roof_height_parameter, ok = self.roof_height_prop.valueAsDouble(
                    context.expressionContext(), roof_height_parameter
                )
                if not ok:
                    feedback.pushWarning("Ignoring feature with wrong roof height")
                    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 polygon in polygons:
                    geom_sfcgal = QgsGeometry_to_SFCGAL(polygon)
                    geom_sfcgal_extrude_straight_skeleton = (
                        geom_sfcgal.extrude_polygon_straight_skeleton(
                            building_height_parameter, roof_height_parameter
                        )
                    )
                    geom_qgis_extrude_extrude_straight_skeleton = SFCGAL_to_QgsGeometry(
                        geom_sfcgal_extrude_straight_skeleton
                    )
                    feature.setGeometry(geom_qgis_extrude_extrude_straight_skeleton)

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

            else:
                geom_sfcgal = QgsGeometry_to_SFCGAL(geom)
                geom_sfcgal_extrude_straight_skeleton = (
                    geom_sfcgal.extrude_polygon_straight_skeleton(
                        building_height_parameter, roof_height_parameter
                    )
                )
                geom_qgis_extrude_extrude_straight_skeleton = SFCGAL_to_QgsGeometry(
                    geom_sfcgal_extrude_straight_skeleton
                )
                feature.setGeometry(geom_qgis_extrude_extrude_straight_skeleton)

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

        return [feature]
