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

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

    The algorithm identifies the common spatial elements shared by two or more layers.
    An intersection represents the portion where features from different layers overlap.
    The algorithm analyzes the geometric relationships, such as points, lines, or polygons,
    within the input layers to precisely determine these intersecting areas.
    The output is a new layer or dataset highlighting the spatial overlap.
    <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_intersection(<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_intersection(@geometry, overlay')) -> 'Polygon ((5.54214262 2.20551277, 5.604 1.233, 7.807 1.575, 7.89321388 2.47591443, 5.54214262 2.20551277))'</li>
    </ul>
    """  # noqa: E501,W505
    geom_input = QgsGeometry_to_SFCGAL(input)
    geom_overlay = QgsGeometry_to_SFCGAL(overlay)

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