from typing import List

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

from .shifted_season_controller import ShiftedSeasonController

from ffx.model.shifted_season import ShiftedSeason


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

    CSS = """

    Grid {
        grid-size: 3 10;
        grid-rows: 2 2 2 2 2 2 2 2 2 2;
        grid-columns: 40 40 40;
        height: 100%;
        width: 100%;
        padding: 1;
    }

    Input {
        border: none;
    }
    Button {
        border: none;
    }

    DataTable {
        min-height: 6;
    }

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

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

    #toplabel {
        height: 1;

    }

        
    .two {
        column-span: 3;
    }
    
    .three {
        column-span: 3;
    }
    
    .four {
        column-span: 4;
    }
    .five {
        column-span: 5;
    }
    .six {
        column-span: 6;
    }
    .seven {
        column-span: 7;
    }

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

    .yellow {
        tint: yellow 40%;
    }
    """

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

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

        self.__ssc = ShiftedSeasonController(context = self.context)

        self.__showId = showId
        self.__patternId = patternId
        self.__shiftedSeasonId = shiftedSeasonId

    def _owner_kwargs(self):
        if self.__patternId is not None:
            return {'patternId': self.__patternId}
        return {'showId': self.__showId}

    def on_mount(self):

        if self.__shiftedSeasonId is not None:
            shiftedSeason: ShiftedSeason = self.__ssc.getShiftedSeason(self.__shiftedSeasonId)

            originalSeason = shiftedSeason.getOriginalSeason()
            self.query_one("#input_original_season", Input).value = str(originalSeason)

            firstEpisode = shiftedSeason.getFirstEpisode()
            self.query_one("#input_first_episode", Input).value = str(firstEpisode) if firstEpisode != -1 else ''

            lastEpisode = shiftedSeason.getLastEpisode()
            self.query_one("#input_last_episode", Input).value = str(lastEpisode) if lastEpisode != -1 else ''

            seasonOffset = shiftedSeason.getSeasonOffset()
            self.query_one("#input_season_offset", Input).value = str(seasonOffset) if seasonOffset else ''

            episodeOffset = shiftedSeason.getEpisodeOffset()
            self.query_one("#input_episode_offset", Input).value = str(episodeOffset) if episodeOffset else ''


    def compose(self):

        yield Header()

        with Grid():

            # 1
            yield Static("Edit shifted season" if self.__shiftedSeasonId is not None else "New shifted season", id="toplabel", classes="three")

            # 2
            yield Static(" ", classes="three")

            # 3
            yield Static("Source season")
            yield Input(id="input_original_season", classes="two")

            # 4
            yield Static("First Episode")
            yield Input(id="input_first_episode", classes="two")

            # 5
            yield Static("Last Episode")
            yield Input(id="input_last_episode", classes="two")

            # 6
            yield Static("Season offset")
            yield Input(id="input_season_offset", classes="two")

            # 7
            yield Static("Episode offset")
            yield Input(id="input_episode_offset", classes="two")

            # 8
            yield Static(" ", classes="three")

            # 9
            yield Button("Save", id="save_button")
            yield Button("Cancel", id="cancel_button")
            yield Static(" ")

            # 10
            yield Static(" ", classes="three")

        yield Footer()


    def getShiftedSeasonObjFromInput(self):

        shiftedSeasonObj = {}

        originalSeason = self.query_one("#input_original_season", Input).value
        if not originalSeason:
            return None
        shiftedSeasonObj['original_season'] = int(originalSeason)

        try:
            shiftedSeasonObj['first_episode'] = int(self.query_one("#input_first_episode", Input).value)
        except ValueError:
            shiftedSeasonObj['first_episode'] = -1

        try:
            shiftedSeasonObj['last_episode'] = int(self.query_one("#input_last_episode", Input).value)
        except ValueError:
            shiftedSeasonObj['last_episode'] = -1

        try:
            shiftedSeasonObj['season_offset'] = int(self.query_one("#input_season_offset", Input).value)
        except ValueError:
            shiftedSeasonObj['season_offset'] = 0

        try:
            shiftedSeasonObj['episode_offset'] = int(self.query_one("#input_episode_offset", Input).value)
        except ValueError:
            shiftedSeasonObj['episode_offset'] = 0

        return shiftedSeasonObj


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

        # Check if the button pressed is the one we are interested in
        if event.button.id == "save_button":

            shiftedSeasonObj = self.getShiftedSeasonObjFromInput()

            if shiftedSeasonObj is not None:

                if self.__shiftedSeasonId is not None:

                    if self.__ssc.checkShiftedSeason(
                        shiftedSeasonObj=shiftedSeasonObj,
                        shiftedSeasonId=self.__shiftedSeasonId,
                        **self._owner_kwargs(),
                    ):
                        if self.__ssc.updateShiftedSeason(self.__shiftedSeasonId, shiftedSeasonObj):
                            self.dismiss((self.__shiftedSeasonId, shiftedSeasonObj))
                        else:
                            #TODO: Meldung
                            self.app.pop_screen()

                else:
                    if self.__ssc.checkShiftedSeason(
                        shiftedSeasonObj=shiftedSeasonObj,
                        **self._owner_kwargs(),
                    ):
                        self.__shiftedSeasonId = self.__ssc.addShiftedSeason(
                            shiftedSeasonObj=shiftedSeasonObj,
                            **self._owner_kwargs(),
                        )
                        self.dismiss((self.__shiftedSeasonId, shiftedSeasonObj))


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