# 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_difference(input, overlay, feature, parent):  # noqa: A002
    """
    <style>
    span { color: red }

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

    Returns the geometric difference between two layers, an input layer and a mask layer.
    More concretely, this returns the part of the input geometry that doesn't intersect
    a part of the mask layer geometry.
    <br/><br/>
    <h1>Auguments</h1>
    <table>
        <tr><td><span>input</span></td><td>geometry</td></tr>
        <tr><td><span>overlay</span></td><td>geometry</td></tr>
    </table>
    <br/><br/>
    <h1>Syntax</h1>
    cg_difference(<span>@geometry</span>,<span>overlay_geometry</span>)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>input -> @geometry -> MULTIPOLYGON (((8.016 3.759, 5.453 3.607, 5.604 1.233, 7.807 1.575, 8.016 3.759)))</li>
        <li>overlay -> MULTIPOLYGON (((5.016 2.145, 8.320 2.525, 8.301 1.195, 5.244 0.949, 5.016 2.145))"</li>
        <li> cg_difference(@geometry, overlay')) -> 'Polygon ((5.45256621 3.60725061, 5.54227644 2.20552816, 7.89359148 2.47595786, 8.01633424 3.7591776, 5.45256621 3.60725061))'</li>
    </ul>
    """  # noqa: E501,W505
    geom_input = QgsGeometry_to_SFCGAL(input)
    geom_overlay = QgsGeometry_to_SFCGAL(overlay)

    result_geom = geom_input.difference(geom_overlay)
    new_geom = SFCGAL_to_QgsGeometry(result_geom)
    return new_geom
