from __future__ import annotations

from collections.abc import Iterable, Generator

import axipy
from PySide2.QtCore import Signal
from axipy._internal._observer_abc import _ObserverABC


class MergePolygonsObserver(_ObserverABC):
    @property
    def name(self) -> str:
        return "ru_axioma_gis_merge_polygons_by_field_MergePolygonsObserver"

    @property
    def signals(self) -> Signal | Iterable[Signal]:
        return (
            axipy.ObserverManager.ActiveMapView.changed,
        )

    def test_value(self) -> bool:
        return (
                axipy.ObserverManager.ActiveMapView.value and
                isinstance(axipy.view_manager.active, axipy.MapView) and  # extra check for axipy.LegendView
                self._test_value()
        )

    @staticmethod
    def active_map_view() -> axipy.MapView:
        """Ensured by observer."""
        return axipy.view_manager.active

    @classmethod
    def get_tables_from_active_map_view(cls) -> Generator[axipy.Table]:
        map_view: axipy.MapView = cls.active_map_view()
        list_layers = map_view.map.layers
        yield from cls._get_tables_from_list_layers(list_layers)

    @classmethod
    def _get_tables_from_list_layers(cls, list_layers: axipy.ListLayers) -> Generator[axipy.Table]:
        for elem in list_layers:
            if isinstance(elem, axipy.VectorLayer):
                yield elem.data_object
            elif isinstance(elem, axipy.ListLayers):
                yield from cls._get_tables_from_list_layers(elem)

    def _test_value(self) -> bool:
        if any(self.get_tables_from_active_map_view()):
            return True

        return False
