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 Channel, Schedule

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


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

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

    @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_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
        return await self._api.get_schedule(channel_id, date)
