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

# QGIS
from qgis.core import QgsGeometry, QgsWkbTypes
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_minkowski_sum(input_a: QgsGeometry, input_b: QgsGeometry, feature, parent):
    """
    <style>
    span { color: red }

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

    This function performs a 2D minkowski sum of a point, line or polygon with a polygon.
    A minkowski sum of two geometries A and B is the set of all points that are the sum
    of any point in A and B
    <br/><br/>
    <h1>Auguments</h1>
    <table>
        <tr><td><span>input A</span></td><td>Any geometry</td></tr>
        <tr><td><span>input B</span></td><td>Polygon geometry</td></tr>
    </table>
    <br/><br/>
    <h1>Syntax</h1>
    cg_minkowski_sum(<span>@geometry</span>,<span>input B</span>)
    <br/><br/>
    <h1>Examples</h1>
    <ul>
        <li>input A-> @geometry -> 'MultiLineString ((5.233 2.246, 7.867 1.278))'</li>
        <li>input B -> 'Polygon ((8.016 3.759, 7.807 1.575, 5.604 1.233, 5.453 3.607, 8.016 3.759))'</li>
        <li> cg_minkowski_sum( geom_from_wkt('MultiLineString ((5.233 2.246, 7.867 1.278))'), geom_from_wkt('Polygon ((8.016 3.759, 7.807 1.575, 5.604 1.233, 5.453 3.607, 8.016 3.759))'))</li>
        <li> result : 'MultiPolygon (((13.249 6.005, 10.686 5.853, 10.837 3.479, 13.471 2.511, 15.674 2.853, 15.883 5.037, 13.249 6.005)))' </li>
    </ul>
    """  # noqa: E501,W505

    if QgsWkbTypes.displayString(input_b.wkbType()) != "Polygon":
        parent.setEvalErrorString(
            "Impossible to calculate expression : the second argument must be a Polygon"
            f" and not {QgsWkbTypes.displayString(input_b.wkbType())}"
        )

    geom_a = QgsGeometry_to_SFCGAL(input_a)
    geom_b = QgsGeometry_to_SFCGAL(input_b)

    try:
        result_geom = geom_a.minkowski_sum(geom_b)
        new_geom = SFCGAL_to_QgsGeometry(result_geom)
        return new_geom
    except TypeError:
        parent.setEvalErrorString(
            "Impossible to calculate expression : please check your expression"
        )
