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

# QGIS
from qgis.core import QgsWkbTypes
from qgis.utils import qgsfunction

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


@qgsfunction(args="auto", group="SFCGAL", register=False)
def cg_optimal_alpha_shapes(
    value, allow_holes: bool, nb_components: int, feature, parent
):
    """
    <style>
    span { color: red }

    </style>
    <h1>Description</h1>

    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.

    <br/><br/>
    <h1>Auguments</h1>
    <table>
        <tr><td><span>input</span></td><td>geometry</td></tr>
        <tr><td><span>allow holes</span></td><td>bool</td></tr>
        <tr><td><span>nb_components</span></td><td>float</td></tr>
    </table>
    <br/><br/>
    <h1>Syntax</h1>
    cg_optimal_alpha_shapes(<span>@geometry</span>,<span>allow holes</span>,<span>nb_components</span>,)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>cg_optimal_alpha_shapes(geom_from_wkt('MultiPoint ((3.3 5.6), (3.4 5.3), (3.6 5.7), (3.6 5.3), (3.4 5.5), (3.8 5.5))'), False,1) -> 'Polygon ((3.4 5.3, 3.4 5.5, 3.3 5.6, 3.6 5.7, 3.8 5.5, 3.6 5.3, 3.4 5.3))'</li>
    </ul>
    """  # noqa: E501,W505

    if not value.wkbType() == QgsWkbTypes.Type.MultiPoint:
        return None

    geom_input = QgsGeometry_to_SFCGAL(value)
    result_geom = geom_input.optimal_alpha_shapes(allow_holes, nb_components)
    new_geom = SFCGAL_to_QgsGeometry(result_geom)
    return new_geom
