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):
    active_picture: Optional[rio.URL] = None

    @rio.event.on_window_size_change
    async def on_window_size_change(self) -> None:
        await self.force_refresh()

    @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.session[services.DatabaseService].get_picture_paths()):
                thumbnail_link = rio.URL(str(link) + "&thumb=1")
                grid.add(
                    rio.Button(
                        rio.Image(
                            thumbnail_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, window_width=self.session.window_width)
        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: Optional[rio.URL]) -> 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()
