# SPDX-FileCopyrightText: 2025 XLeitstelle Planen und Bauen <xleitstelle@gv.hamburg.de>
# SPDX-FileContributor: Michael Holzapfel <michael.holzapfel@geocledian.com>
#
# SPDX-License-Identifier: EUPL-1.2
from typing import List

from qgis._core import QgsLayerTreeGroup, QgsMapLayer, QgsProject
from qgis.core import QgsCoordinateReferenceSystem
from qgis.PyQt.QtWidgets import QTableView, QHeaderView


class TopoTableView(QTableView):
    """
    Base Class for TableViews
    """

    def __init__(self, parent=None):
        super().__init__(parent)

        # placeholder for CRS
        self.plan_crs: QgsCoordinateReferenceSystem | None = None
        self.verticalHeader().setVisible(False)

        # self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        # self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.horizontalHeader().setStretchLastSection(True)


def get_layer_group_hierarchy(vector_layer: QgsMapLayer) -> List[QgsLayerTreeGroup]:
    """
    Return the hierarchy of groups that the given vector layer belongs to.
    :param vector_layer: QgsMapLayer, The layer whose groups should be retrieved.
    :return: list[QgsLayerTreeGroup], Ordered list of groupsfrom the top‑most group down to the immediate parent of the layer.
             If the layer is not inside any group, an empty list is returned.
    """

    root = QgsProject.instance().layerTreeRoot()
    layer_node = root.findLayer(vector_layer.id())

    if layer_node is None:
        # The layer is not present in the current project tree
        raise ValueError("Layer not found in the current QGIS project.")

    # walk up tree, collect group names
    groups = []
    parent = layer_node.parent()
    while isinstance(parent, QgsLayerTreeGroup):
        # skip root node
        if parent != root:
            groups.append(parent)
        parent = parent.parent()

    # reverse group list, outer group first
    groups.reverse()
    return groups
