from __future__ import annotations

from functools import partial
from typing import *  # type: ignore

import rio

from .page_builder import build_page
from .. import components as comps, services


class Pics(rio.Component):
    def __init__(self, database_service: services.database_service.DatabaseService) -> None:
        super().__init__()
        self._database_service = database_service
        self._active_picture: Optional[rio.URL] = None

    @rio.event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title("EZ GG e.V. - Galerie")

    def build(self) -> rio.Component:
        if self._active_picture is None:
            grid = rio.Grid(row_spacing=0.4, column_spacing=0.5, margin_right=1)
            for i, link in enumerate(self._database_service.get_picture_paths()):
                grid.add(
                    rio.Button(
                        rio.Image(
                            link,
                            height=12,
                            width=12
                        ),
                        shape="rectangle",
                        style="plain",
                        on_press=partial(self.on_picture_clicked, link)
                    ),
                    row=i // 3,
                    column=i % 3,
                )
            return build_page(grid)
        return rio.Overlay(
            rio.Column(
                rio.Button(
                    rio.Image(
                        self._active_picture,
                        height="grow",
                        width="grow"
                    ),
                    shape="rectangle",
                    style="plain",
                    height="grow",
                    on_press=self.exit_overlay
                ),
                rio.Text("Click to exit", margin_bottom=2)
            )
        )

    async def on_picture_clicked(self, link_to_picture: str) -> None:
        self._active_picture = link_to_picture
        await self.force_refresh()

    async def exit_overlay(self) -> None:
        self._active_picture = None
        await self.force_refresh()
