# 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-or-later

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

from xmas_plugin.plan_manager import PlanManager
from xmas_plugin.util.metadata import PLUGIN_DIR_NAME


class AddTexte(QgsMapLayerAction):
    def __init__(self, parent: QObject | None = None):
        super().__init__(
            "Texte hinzufügen",
            parent,
            Qgis.MapLayerActionTarget.SingleFeature,
            QgsApplication.instance().getThemeIcon("mActionTextInsideRect.svg"),
            Qgis.MapLayerActionFlags(),
        )
        self.feature = None
        self.layer = None
        self.triggeredForFeatureV2.connect(self._setup)

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

    @pyqtSlot("QgsMapLayer*", QgsFeature, QgsMapLayerActionContext)
    def _setup(
        self,
        layer: QgsMapLayer,
        feature: QgsFeature,
        _: QgsMapLayerActionContext,
    ) -> None:
        self.layer = layer
        self.feature = feature
        self._add_texte()

    def _add_texte(self):
        root = QgsProject.instance().layerTreeRoot()
        group = root.findLayer(self.layer.id()).parent()
        PlanManager().build_content_group(
            group=group,
            types=["text"],
            plan_id=self.feature["id"],
            parent_id=self.feature["id"],
            appschema=self.feature["appschema"],
            version=self.feature["version"],
        )
        self.layer = None
        self.feature = None
        iface.messageBar().pushSuccess("Texte", "Textlayer hinzugefügt")
