<gh_stars>1-10
from nonebot import get_driver, on_regex
from nonebot.adapters.cqhttp import Bot
from nonebot.adapters.cqhttp.event import PrivateMessageEvent
from tortoise import Tortoise

from . import data_source as source

driver = get_driver()


@driver.on_shutdown
async def _():
    '''关机断开数据库'''
    await Tortoise.close_connections()


# 获取帮助
get_help = on_regex(pattern=r"^帮助$", permission=source.ADMIN, priority=1, block=True)
# 生成一条万能授权码
create_one = on_regex(pattern=r"^授权", permission=source.ADMIN, priority=1, block=True)
# 生成指定数量的授权码
create_nums = on_regex(pattern=r"^授权 [1-9]$", permission=source.ADMIN, priority=1, block=True)
# 绑定授权
bind_access = on_regex(pattern=r"^绑定授权 [0-9]+$", permission=source.ADMIN, priority=1, block=True)


@get_help.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
    '''管理私聊获取帮助'''
    msg = "管理菜单\n"
    msg += "指令 | 授权 | 生成一条不需要验证的万能授权码\n"
    msg += "指令 | 授权 [1-9] | 生成指定数量的万能授权码\n"
    msg += "指令 | 绑定授权 QQ号码 | 生成一个与该QQ绑定的授权码"
    await get_help.finish(msg)


@create_one.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
    '''生成一条万能授权码'''
    user_id = event.user_id
    token = await source.create_one_token(user_id)
    msg = f"创建成功，生成授权码为：\n{token}"
    await create_one.finish(msg)


@create_nums.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
    '''生成指定数量的授权码'''
    user_id = event.user_id
    num = int(event.get_plaintext().split(' ')[-1])
    token_list = await source.create_num_token(user_id, num)
    msg = f"创建 {num} 个授权码，为：\n"
    for i in range(num):
        msg += f"{token_list[i]}\n"
    await create_nums.finish(msg)


@bind_access.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
    '''生成绑定授权码'''
    user_id = int(event.get_plaintext().split(' ')[-1])
    token = await source.create_bind_token(user_id)
    msg = f"创建绑定[{str(user_id)}]成功，生成授权码为：\n{token}"
    await bind_access.finish(msg)
