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

# QGIS
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,
    # helpText=(
    #     "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. "
    #     "To enter, you need to provide point or multipoint geometry. "
    # ),
)
def cg_convexhull(value, feature, parent):
    """
    <style>
    span { color: red }

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

    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.
    To enter, you need to provide multipoint geometry (or point but return same point).
    <br/><br/>
    <h1>Auguments</h1>
    <table>
        <tr><td><span>geometry</span></td><td>MultiPoint geometry</td></tr>
    </table>
    <br/><br/>
    <h1>Syntax</h1>
    cg_convexhull(<span>@geometry</span>)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>Point (4.43262616 6.7363641) -> Point (4.43262616 6.7363641)</li>
        <li>MultiPoint((35.123 -115.456)) -> Point(35.123 -115.456)</li>
        <li>MultiPoint ((5.0130 6.0070),(6.4568 5.3670)) -> LineString (5.0130 6.0070, 6.4568 5.3670)</li>
        <li>MultiPoint ((4.432 6.736),(6.397 6.825),(3.762 5.649),(5.123 5.634)) -> Polygon ((3.762 5.649, 5.123 5.634, 6.397 6.825, 4.4326 6.736, 3.762 5.649))</li>
    </ul>
    """  # noqa: E501,W505
    geom_input = QgsGeometry_to_SFCGAL(value)
    if geom_input.geom_type not in ["Point", "MultiPoint"]:
        return None

    result_geom = geom_input.convexhull()
    new_geom = SFCGAL_to_QgsGeometry(result_geom)
    return new_geom
