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

from .show_controller import ShowController

from .show_details_screen import ShowDetailsScreen
from .show_delete_screen import ShowDeleteScreen

from ffx.show_descriptor import ShowDescriptor

from textual.widgets._data_table import CellDoesNotExist


class ShowsScreen(Screen):

    CSS = """

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

    DataTable .datatable--cursor {
        background: darkorange;
        color: black;
    }

    DataTable .datatable--header {
        background: steelblue;
        color: white;
    }

    #top {
        height: 1;
    }


    #two {
        column-span: 2;
        row-span: 2;
        tint: magenta 40%;
    }

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

    BINDINGS = [
        ("e", "edit_show", "Edit Show"),
        ("n", "new_show", "New Show"),
        ("d", "delete_show", "Delete Show"),
    ]



    def __init__(self):
        super().__init__()

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

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


    def getSelectedShowId(self):

        try:
            # Fetch the currently selected row when 'Enter' is pressed
            #selected_row_index = self.table.cursor_row
            row_key, col_key = self.table.coordinate_to_cell_key(self.table.cursor_coordinate)

            if row_key is not None:
                selected_row_data = self.table.get_row(row_key)
                
                return selected_row_data[0]

        except CellDoesNotExist:
            return None




    def action_new_show(self):
        self.app.push_screen(ShowDetailsScreen(), self.handle_new_screen)

    def handle_new_screen(self, screenResult):

        show = (screenResult['id'], screenResult['name'], screenResult['year'])
        self.table.add_row(*map(str, show))


    def action_edit_show(self):
            
            selectedShowId = self.getSelectedShowId()

            if selectedShowId is not None:
                self.app.push_screen(ShowDetailsScreen(showId = selectedShowId), self.handle_edit_screen)


    def handle_edit_screen(self, showDescriptor: ShowDescriptor):

        try:

            row_key, col_key = self.table.coordinate_to_cell_key(self.table.cursor_coordinate)

            self.table.update_cell(row_key, self.column_key_name,  showDescriptor.getName())
            self.table.update_cell(row_key, self.column_key_year,  showDescriptor.getYear())        

        except CellDoesNotExist:
            pass




    def action_delete_show(self):
            
        selectedShowId = self.getSelectedShowId()

        if selectedShowId is not None:
            self.app.push_screen(ShowDeleteScreen(showId = selectedShowId), self.handle_delete_show)


    def handle_delete_show(self, showDescriptor: ShowDescriptor):

        try:
            row_key, col_key = self.table.coordinate_to_cell_key(self.table.cursor_coordinate)
            self.table.remove_row(row_key)

        except CellDoesNotExist:
            pass


    def on_mount(self) -> None:
        for show in self.__sc.getAllShows():
            row = (int(show.id), show.name, show.year) # Convert each element to a string before adding
            self.table.add_row(*map(str, row))


    def compose(self):

        # Create the DataTable widget
        self.table = DataTable()

        # Define the columns with headers
        self.column_key_id = self.table.add_column("ID", width=10)
        self.column_key_name = self.table.add_column("Name", width=50)
        self.column_key_year = self.table.add_column("Year", width=10)

        self.table.cursor_type = 'row'

        yield Header()

        with Grid():

            yield Static("Shows")

            yield self.table

        f = Footer()
        f.description = "yolo"

        yield f
