# geometry_utils.py

import math
import processing
from math import ceil

from qgis.core import (
    QgsGeometry,
    QgsPointXY, QgsPoint
)


def vzdalenost(p1, p2):
    """
    Vzdálenost dvou bodů.
    """

    return math.sqrt(
        (p2.x() - p1.x()) ** 2 +
        (p2.y() - p1.y()) ** 2
    )


def vypocet_uhlu(p1, p2, p3):
    """
    Výpočet úhlu mezi třemi body.
    """

    a = vzdalenost(p2, p3)
    b = vzdalenost(p1, p3)
    c = vzdalenost(p1, p2)

    if a == 0 or c == 0:
        return 0

    cos_uhel = (a**2 + c**2 - b**2) / (2 * a * c)

    cos_uhel = max(-1, min(1, cos_uhel))

    return math.degrees(math.acos(cos_uhel))


def odstranit_z_souradnice(geom):
    """
    Odebere Z souřadnici z geometrie.
    """

    geom = QgsGeometry(geom)

    if geom.isMultipart():
        body = []

        for line in geom.asMultiPolyline():
            body.append([
                QgsPointXY(pt.x(), pt.y())
                for pt in line
            ])

        return QgsGeometry.fromMultiPolylineXY(body)

    else:
        body = [
            QgsPointXY(pt.x(), pt.y())
            for pt in geom.asPolyline()
        ]

        return QgsGeometry.fromPolylineXY(body)



def clip_lyr(lyr, lyr_orez, dissolving=False):

    lyr_bool = False
    lyr_clip =processing.run("native:clip", {
    'INPUT': lyr,
    'OVERLAY': lyr_orez,
    'OUTPUT': 'TEMPORARY_OUTPUT'})["OUTPUT"]
    if lyr_clip.featureCount() > 0:
        lyr_bool = True
        if dissolving:
            lyr_clip = processing.run("native:dissolve", {'INPUT':lyr_clip,'FIELD':[],'SEPARATE_DISJOINT':False,'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]

    return lyr_clip, lyr_bool



def rozdel_krivku_na_segmenty(line_geometry, delka_segmentu):

    if line_geometry.isMultipart():
        parts = line_geometry.asMultiPolyline()
    else:
        parts = [line_geometry.asPolyline()]

    segments = []

    for part in parts:

        part_geom = QgsGeometry.fromPolylineXY(part)
        delka = part_geom.length()

        if delka == 0:
            continue

        pocet = ceil(delka / delka_segmentu)

        prvni = part[0]
        posledni = part[-1]

        if (
posledni.x() < prvni.x() or (posledni.x() == prvni.x() and posledni.y() < prvni.y())):
            pocatek = posledni
        else:
            pocatek = prvni

        if part_geom.interpolate(0).asPoint() == pocatek:
            vzdalenost0 = 10
        else:
            vzdalenost0 = delka - (pocet - 1) * delka_segmentu

        vzdalenost = 0

        while vzdalenost < delka:

            start_point = QgsPoint(part_geom.interpolate(vzdalenost).asPoint())

            if vzdalenost == 0:
                segments.append(start_point)

                next_point = QgsPoint(
                    part_geom.interpolate(
                        min(vzdalenost + vzdalenost0, delka)
                    ).asPoint()
                )

                vzdalenost += vzdalenost0
                segments.append(next_point)

            else:
                next_point = QgsPoint(
                    part_geom.interpolate(
                        min(vzdalenost + delka_segmentu, delka)
                    ).asPoint()
                )

                vzdalenost += delka_segmentu
                segments.append(next_point)

    return segments



