from rio import Column, Component, event, TextStyle, Text, Spacer, ProgressCircle

from src.ezgg_lan_manager import ConfigurationService, TournamentService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.components.TournamentPageRow import TournamentPageRow
from src.ezgg_lan_manager.types.Tournament import Tournament


class TournamentsPage(Component):
    tournament_data: list[Tournament] = []

    @event.on_populate
    async def on_populate(self) -> None:
        self.tournament_data = await self.session[TournamentService].get_tournaments()
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Turniere")

    def tournament_clicked(self, tournament_id: int) -> None:
        self.session.navigate_to(f"tournament?id={tournament_id}")

    def build(self) -> Component:
        tournament_page_rows = []
        for tournament in self.tournament_data:
            tournament_page_rows.append(
                TournamentPageRow(
                    tournament.id,
                    tournament.name,
                    tournament.game_title.image_name,
                    len(tournament.participants),
                    tournament.max_participants,
                    tournament.status,
                    self.tournament_clicked
                )
            )

        if len(self.tournament_data) == 0:
            content = [Column(
                ProgressCircle(
                    color="secondary",
                    align_x=0.5,
                    margin_top=0,
                    margin_bottom=0
                ),
                min_height=10
            )]
        else:
            content = tournament_page_rows

        return Column(
            MainViewContentBox(
                Column(
                    Text(
                        text="Turniere",
                        style=TextStyle(
                            fill=self.session.theme.background_color,
                            font_size=1.2
                        ),
                        margin_top=2,
                        margin_bottom=2,
                        align_x=0.5
                    ),
                    *content,
                    Spacer(min_height=1)
                )
            ),
            align_y=0
        )
