import nonebot
from nonebot_plugin_alconna import Alconna, Args, on_alconna

from konabot.common.longtask import DepLongTaskTarget
from konabot.common.pager import PagerQuery
from konabot.common.subscribe import POSTER_INFO_DATA, dep_poster_service


cmd_subscribe = on_alconna(
    Alconna(
        "订阅",
        Args["channel", str],
    )
)


@cmd_subscribe.handle()
async def _(target: DepLongTaskTarget, channel: str):
    async with dep_poster_service() as service:
        result = await service.subscribe(channel, target)
    if result:
        await target.send_message(f"已订阅「{channel}」")
    else:
        await target.send_message(f"已经订阅过「{channel}」了")


cmd_list = on_alconna(
    Alconna(
        "re:(?:查询|我的|获取)订阅(列表)?",
        Args["page?", int],
    )
)


def better_channel_message(channel_id: str) -> str:
    if channel_id not in POSTER_INFO_DATA:
        return channel_id
    data = POSTER_INFO_DATA[channel_id]
    return f"{channel_id}：{data.description}"


@cmd_list.handle()
async def _(target: DepLongTaskTarget, page: int = 1):
    async with dep_poster_service() as service:
        result = await service.get_channels(
            target,
            PagerQuery(
                page_index=page,
                page_size=10,
            ),
        )
        await target.send_message(
            result.to_unimessage(title="订阅列表", formatter=better_channel_message)
        )


cmd_list_available = on_alconna(
    Alconna(
        "re:(查询)?可用订阅(列表)?",
        Args["page?", int],
    )
)


@cmd_list_available.handle()
async def _(target: DepLongTaskTarget, page: int = 1):
    result = PagerQuery(
        page_index=page,
        page_size=10,
    ).apply(sorted(POSTER_INFO_DATA.keys()))
    await target.send_message(
        result.to_unimessage(title="可用订阅列表", formatter=better_channel_message)
    )


cmd_unsubscribe = on_alconna(
    Alconna(
        "取消订阅",
        Args["channel", str],
    )
)


@cmd_unsubscribe.handle()
async def _(target: DepLongTaskTarget, channel: str):
    async with dep_poster_service() as service:
        result = await service.subscribe(channel, target)
    if result:
        await target.send_message(f"已取消订阅「{channel}」")
    else:
        await target.send_message(f"这里没有订阅过「{channel}」")


driver = nonebot.get_driver()


@driver.on_startup
async def _():
    async with dep_poster_service() as service:
        await service.fix_data()
