# 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,
)
def cg_force_lhr(value, feature, parent):
    """
    <style>
    span { color: red }

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

    Forces the orientation of the vertices in a polygon to follow a Left-Hand-Rule, in
    which the area that is bounded by the polygon is to the left of the boundary. In
    particular, the exterior ring is orientated in a clockwise direction and the interior
    rings in a counter-clockwise direction.
    <br/><br/>
    <h1>Auguments</h1>
    <table>
        <tr><td><span>geometry</span></td><td>Polygon/MultiPolygon geometry</td></tr>
    </table>
    <br/><br/>
    <h1>Syntax</h1>
    cg_force_lhr(<span>@geometry</span>)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>Input: 'MultiPolygon (((8.016 3.759, 7.807 1.575, 5.604 1.233, 5.453 3.607, 8.016 3.759)))'</li>
        <li>Output: 'MultiPolygon (((8.016 3.759, 5.453 3.607, 5.604 1.233, 7.807 1.575, 8.016 3.759)))'</li>
    </ul>
    """  # noqa: E501,W505
    geom_input = QgsGeometry_to_SFCGAL(value)
    if geom_input.geom_type not in ["Polygon", "MultiPolygon"]:
        return None
    result_geom = geom_input.force_lhr()
    new_geom = SFCGAL_to_QgsGeometry(result_geom)
    return new_geom
