import json
from typing import Dict
from nonebot import on_command
from nonebot.plugin import on_keyword
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event, event

record = on_command("记录",aliases={'note'},rule=to_me(),priority=5)

@record.handle()
async def recordMain(bot: Bot, event: Event, state: dict):
    await record.send("你需要记录什么呢？",at_sender=True)    

@record.receive()
async def recordTwo(bot: Bot, event: Event, state: dict):
    info = str(event.get_message())
    users = await openfile()
    users[event.get_user_id()] = info
    await writefile(users)
    await record.finish("记录成功!")



search = on_command("查看",aliases={"find"},rule=to_me(),priority=5)

@search.handle()
async def searchMain(bot: Bot, event: Event, state: dict):
    users = await openfile()
    if event.get_user_id() not in users:
        await search.send("很抱歉，您没有记录任何东西",at_sender=True)
    else:
        await search.send("您之前的记录如下：",at_sender=True)
        await search.send(f"{users[event.get_user_id()]}",at_sender=True)
    await search.finish()

clear = on_command('清除',aliases={'cls','clear'},rule=to_me(),priority=5)
@clear.handle()
async def clearMain(bot:Bot, event:Event, state:Dict):
    users = await openfile()
    user = event.get_user_id()
    if user in users:
        del users[user]
        await writefile(users)
        await clear.send("清除成功！",at_sender=True)
    else:
        await clear.send("抱歉，您之前没有任何记录！",at_sender = True)
    await clear.finish()





async def openfile():
    with open("src/plugins/note/data.json", 'r') as f:
        users = json.load(f)
    return users

async def writefile(users):
    with open("src/plugins/note/data.json", 'w') as f:
            json.dump(users,f)
