# 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 AddContent(QgsMapLayerAction):
    def __init__(self, parent: QObject | None = None):
        super().__init__(
            "Layerbaum hinzufügen",
            parent,
            Qgis.MapLayerActionTarget.SingleFeature,
            QgsApplication.instance().getThemeIcon("mIconTreeView.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") == "section"
            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_content()

    def _add_content(self):
        root = QgsProject.instance().layerTreeRoot()
        group = root.findLayer(self.layer.id()).parent()
        PlanManager().build_content_group(
            group=group,
            types=["subject", "presentation"],
            plan_id=self.layer.customProperty(f"{PLUGIN_DIR_NAME}/plan_id"),
            parent_id=self.feature["id"],
            appschema=self.feature["appschema"],
            version=self.feature["version"],
        )
        iface.messageBar().pushSuccess(
            f"Bereich {self.feature['properties']['nummer']}", "Layerbaum hinzugefügt"
        )
        self.layer = None
        self.feature = None
