#
#   Imandra Inc.
#
#   facet_view.py
#

from textual import on
from textual.containers import HorizontalGroup, VerticalScroll
from textual.reactive import reactive
from textual.screen import Screen
from textual.widgets import Button, Footer, Label, Rule, Static

from codelogician.modeling.metamodel import MetaModel
from codelogician.modeling.model import Model
from codelogician.util import fst

from ..common import Border, MyHeader, bind


class FacetViewScreen(Screen):
    """ """

    mmodel: reactive[None | MetaModel] = reactive(None, recompose=True)

    def __init__(self, get_views, kind, title):
        Screen.__init__(self)
        self.tagged_models: list[tuple[str, tuple[str, Model]]] = []
        self.model_by_button_id = {}
        self.title = title
        self.kind = kind
        self.get_views = get_views
        bind(self, 'mmodel')

    def watch_mmodel(self, _: MetaModel, mmodel: MetaModel):
        if mmodel:
            models = sorted(mmodel.models.items(), key=fst)
            self.tagged_models = [(f'view_{i}', pm) for i, pm in enumerate(models)]
            self.model_by_button_id = dict(self.tagged_models)
        else:
            self.tagged_models = []

    def compose(self):
        """ """
        yield MyHeader()
        with VerticalScroll():
            for b_id, (path, model) in self.tagged_models:
                yield Rule()
                with HorizontalGroup():
                    yield Button('View', variant='primary', id=b_id, compact=True)
                    yield Label(f' Model path: [$primary][b]{path}[/b][/]')

                views = self.get_views(model)
                if len(views) > 0:
                    yield Static()
                    with VerticalScroll() as vs:
                        vs.styles.height = 'auto'
                        vs.styles.max_height = '75%'
                        for i, v in enumerate(views):
                            yield (
                                v
                                if self.kind is None
                                else Border(f'{self.kind} #{i + 1}', v)
                            )
        yield Footer()

    @on(Button.Pressed)
    async def switch_to_model(self, event: Button.Pressed):
        if event.button.id is not None:
            path, _ = self.model_by_button_id[event.button.id]
            await self.app.switch_to_model(path)  # pyright: ignore
