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

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

    The union algorithm returns all entities from the input layer. If a geometry
    from the input layer intersects with another from the overlay layer, these two
    geometries are returned merged. Geometries from the overlay layer that do not
    intersect with any geometry from the input layer are not returned.
    <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_union(<span>@geometry</span>,<span>overlay_geometry</span>)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>input -> @geometry -> MultiPolygon (((2.827 0.887, 2.802 0.431, 1.03 0.621, 0.789 -0.607, 2.549 -0.632, 2.587 -1.291, 0.384 -1.164, 0.688 0.887, 2.827 0.887)))</li>
        <li>overlay -> MultiPolygon (((1.06 1.675, 1.983 1.72, 1.849 0.961, 1.477 0.217, 1.179 -0.036, 0.48 -0.2, -0.473 -0.096, -0.681 0.366, 1.06 1.675)))</li>
        <li> cg_union(@geometry, overlay')) -> ''Polygon ((2.587 -1.291, 2.549 -0.632, 0.789 -0.607, 0.88764557 -0.10435783, 1.179 -0.036, 1.477 0.217, 1.64597643 0.55495287, 2.802 0.431, 2.827 0.887, 1.812 0.887, 1.849 0.961, 1.983 1.72, 1.06 1.675, -0.681 0.366, -0.473 -0.096, 0.48 -0.2, 0.52857362 -0.18860361, 0.384 -1.164, 2.587 -1.291))''</li>
    </ul>
    """  # noqa: E501,W505
    geom_input = QgsGeometry_to_SFCGAL(input)
    geom_overlay = QgsGeometry_to_SFCGAL(overlay)

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