from axipy.da import Table
from axipy.gui import MapView
from axipy.render import Layer
from PySide2.QtWidgets import QComboBox, QVBoxLayout, QWidget


class TableSelector(QWidget):
    """
    Виджет со списком слоёв с текущей карты.
    """

    def __init__(self, map_view: MapView, parent: QWidget = None) -> None:
        super().__init__(parent)
        self.__map_view = map_view
        self.__cb = QComboBox(self)  # type: QComboBox
        vlayout = QVBoxLayout(self)
        vlayout.setContentsMargins(9, 0, 9, 0)
        vlayout.setSpacing(0)
        vlayout.addWidget(self.__cb)
        self.setLayout(vlayout)
        self.__fill_combobox(map_view)

    def select(self, title: str):
        pos = self.__cb.findText(title)
        if pos == -1:
            return
        self.__cb.setCurrentIndex(pos)

    @property
    def selected_table(self) -> Table:
        """
        Выбранная таблица
        """
        return self.__cb.currentData()

    def refresh(self):
        """
        Перечитывает список слоёв из карты
        """
        self.__fill_combobox(self.__map_view)

    def __fill_combobox(self, map_view: MapView):

        def is_table(t: Table):
            return t is not None and isinstance(t, Table) and t.is_spatial

        def add_item(layer_arg: Layer):
            data_object = layer_arg.data_object
            if not isinstance(data_object, Table):
                return None
            if layer_arg and is_table(data_object):
                self.__cb.addItem(layer_arg.title, layer_arg.data_object)

        self.__cb.clear()
        add_item(self.__map_view.map.cosmetic)
        for layer in map_view.map.layers:
            add_item(layer)

        # под индексом 0 всегда косметика
        first_non_cosmetic_layer_index = 1
        if self.__cb.count() > 1:
            self.__cb.setCurrentIndex(first_non_cosmetic_layer_index)
