import datetime
from pathlib import Path

from fastapi import APIRouter
from fastapi.responses import HTMLResponse, RedirectResponse

from gallery.easel.core import AppRequest
from gallery.sketch.schedule.catalog import BUNDLE

from ..common.utils.tag import TagType, TagUtil
from ..common.utils.template import build_templates
from .filters import timedelta_format

templates = build_templates(
    Path(__file__).parent / "templates",
    {
        "timedelta_format": timedelta_format,
    },
)

router = APIRouter()


@router.get("/schedule", response_class=HTMLResponse)
async def get_schedule_list(request: AppRequest):
    schedule_api = request.app.state.api.schedule
    channels = await schedule_api.get_channels()
    channels_data = BUNDLE.select_items(channels)
    return templates.TemplateResponse(
        request=request,
        name="index.html",
        context={
            "channels": channels_data,
        },
    )


@router.get("/schedule/tag/{tag}", response_class=HTMLResponse)
async def get_schedule_tag(request: AppRequest, tag: str, live: bool = False):
    tag_value = TagUtil.parse_tag(tag)
    schedule_api = request.app.state.api.schedule
    results = await schedule_api.get_all_schedules(tag_value.date)
    return templates.TemplateResponse(
        request=request,
        name="schedule.html",
        context={
            "tag_util": TagUtil,
            "datetime": datetime,
            "response": results[0],
            "responses": results,
            "live": live,
        },
    )


@router.get("/schedule/{channel}", response_class=RedirectResponse)
async def get_channel_default(channel: str):
    return RedirectResponse(f"{channel}/tag/today")


@router.get("/schedule/{channel}/tag/{tag}", response_class=HTMLResponse)
async def get_channel_tag(request: AppRequest, channel: str, tag: str):
    tag_value = TagUtil.parse_tag(tag)
    schedule_api = request.app.state.api.schedule
    if tag_value.type == TagType.DAY:
        response = await schedule_api.get_channel_schedule(channel, tag_value.date)
    else:
        raise ValueError(tag)
    return templates.TemplateResponse(
        request=request,
        name="channel.html",
        context={
            "tag_util": TagUtil,
            "datetime": datetime,
            "response": response,
        },
    )
