import click

from textual.screen import Screen
from textual.widgets import Header, Footer, Static, Button
from textual.containers import Grid

from .show_controller import ShowController
from .pattern_controller import PatternController

from ffx.model.pattern import Pattern


# Screen[dict[int, str, int]]
class PatternDeleteScreen(Screen):

    CSS = """

    Grid {
        grid-size: 2;
        grid-rows: 2 auto;
        grid-columns: 30 330;
        height: 100%;
        width: 100%;
        padding: 1;
    }

    Input {
        border: none;
    }
    Button {
        border: none;
    }
    #toplabel {
        height: 1;
    }

    .two {
        column-span: 2;
    }

    .box {
        height: 100%;
        border: solid green;
    }
    """

    def __init__(self, patternId = None, showId = None):
        super().__init__()

        self.context = self.app.getContext()
        self.Session = self.context['database']['session'] # convenience

        self.__pc = PatternController(context = self.context)
        self.__sc = ShowController(context = self.context)

        self.__patternId = patternId
        self.__pattern: Pattern = self.__pc.getPattern(patternId) if patternId is not None else {}
        self.__showDescriptor = self.__sc.getShowDescriptor(showId) if showId is not None else {}


    def on_mount(self):
        if self.__showDescriptor:
            self.query_one("#showlabel", Static).update(f"{self.__showDescriptor.getId()} - {self.__showDescriptor.getName()} ({self.__showDescriptor.getYear()})")
        if not self.__pattern is None:
            self.query_one("#patternlabel", Static).update(str(self.__pattern.pattern))


    def compose(self):

        yield Header()

        with Grid():

            yield Static("Are you sure to delete the following filename pattern?", id="toplabel", classes="two")

            yield Static("", classes="two")
            
            yield Static("Pattern")
            yield Static("", id="patternlabel")

            yield Static("", classes="two")

            yield Static("from show")
            yield Static("", id="showlabel")

            yield Static("", classes="two")

            yield Button("Delete", id="delete_button")
            yield Button("Cancel", id="cancel_button")

        yield Footer()


   # Event handler for button press
    def on_button_pressed(self, event: Button.Pressed) -> None:

        if event.button.id == "delete_button":

            if self.__patternId is None:
                raise click.ClickException('PatternDeleteScreen.on_button_pressed(): pattern id is undefined')

            if self.__pc.deletePattern(self.__patternId):
                self.dismiss(self.__pattern)

            else:
                #TODO: Meldung
                self.app.pop_screen()

        if event.button.id == "cancel_button":
            self.app.pop_screen()

