# SPDX-FileCopyrightText: 2025 XLeitstelle Planen und Bauen <xleitstelle@gv.hamburg.de>
# SPDX-FileContributor: Tobias Kraft <tobias.kraft@gv.hamburg.de>
#
# SPDX-License-Identifier: EUPL-1.2

from qgis.core import (
    Qgis,
    QgsApplication,
    QgsFeature,
    QgsMapLayer,
    QgsVectorLayer,
)
from qgis.gui import (
    QgsMapLayerAction,
    QgsMapLayerActionContext,
)
from qgis.PyQt.QtCore import QObject, pyqtSlot
from qgis.utils import iface

from xmas_plugin.util.metadata import PLUGIN_DIR_NAME


class CopyGeometry(QgsMapLayerAction):
    def __init__(self, parent: QObject | None = None):
        super().__init__(
            "Geometrie in Zwischenablage kopieren",
            parent,
            Qgis.MapLayerActionTargets(
                Qgis.MapLayerActionTarget.SingleFeature
                | Qgis.MapLayerActionTarget.MultipleFeatures
            ),
            QgsApplication.instance().getThemeIcon("mActionEditCopy.svg"),
            Qgis.MapLayerActionFlags(),
        )
        self._running = False
        self.triggeredForFeatureV2.connect(self._trigger_for_feature)
        self.triggeredForFeaturesV2.connect(self._trigger_for_features)

    def canRunUsingLayer(
        self,
        layer: QgsMapLayer | None,
        _: QgsMapLayerActionContext = QgsMapLayerActionContext(),
    ) -> bool:
        return (
            layer.customProperty(f"{PLUGIN_DIR_NAME}/layer_type") is not None
            if layer
            else False
        )

    @pyqtSlot("QgsMapLayer*", QgsFeature, QgsMapLayerActionContext)
    def _trigger_for_feature(
        self,
        layer: QgsMapLayer,
        feature: QgsFeature,
        _: QgsMapLayerActionContext,
    ) -> None:
        self._copy_geometries(layer, [feature])

    @pyqtSlot("QgsMapLayer*", "QList<QgsFeature>", QgsMapLayerActionContext)
    def _trigger_for_features(
        self,
        layer: QgsMapLayer,
        features: list[QgsFeature],
        _: QgsMapLayerActionContext,
    ) -> None:
        self._copy_geometries(layer, features)

    def _copy_geometries(
        self,
        layer: QgsMapLayer,
        features: list[QgsFeature],
    ) -> None:
        temp_layer = QgsVectorLayer(
            f"{layer.wkbType().name}?crs={layer.crs().authid()}", "temp", "memory"
        )
        print("valid", temp_layer.isValid())
        temp_provider = temp_layer.dataProvider()
        temp_features = []
        for feature in features:
            temp_feature = QgsFeature()
            temp_feature.setGeometry(feature.geometry())
            temp_features.append(temp_feature)
        temp_provider.addFeatures(temp_features)
        temp_layer.selectAll()
        iface.copySelectionToClipboard(temp_layer)
        print(temp_layer.selectedFeatureCount())
