import datetime

from aiocache import cached

from gallery.sketch.cached import CachedApi, CachePreset
from gallery.util import TimeUnit

from .api import ScheduleApi
from .model import ChannelId, Schedule

CACHE_PRESET = CachePreset(ttl=TimeUnit.HOUR * 6)


class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]):
    CACHE_KEY = ScheduleApi.TYPE

    @cached(
        key_builder=lambda fun, self: f"api.{self.CACHE_KEY}.{self.provider}.channels",
        **CACHE_PRESET._asdict(),
    )
    async def get_channels(self) -> list[ChannelId]:
        return await self._api.get_channels()

    @cached(
        key_builder=lambda fun, self, channel_id, date: (
            f"api.{self.CACHE_KEY}.{self.provider}.channel.{channel_id}.{date}"
        ),
        **CACHE_PRESET._asdict(),
    )
    async def get_channel_schedule(self, channel_id: ChannelId, date: datetime.date) -> Schedule:
        return await self._api.get_channel_schedule(channel_id, date)

    @cached(
        key_builder=lambda fun, self, date: (f"api.{self.CACHE_KEY}.{self.provider}.all.{date}"),
        **CACHE_PRESET._asdict(),
    )
    async def get_all_schedules(self, date: datetime.date) -> list[Schedule]:
        return await self._api.get_all_schedules(date)
