from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, Bot, MessageSegment
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me

from .data_proc import *
from .img_generator import *
import io
import base64

__plugin_meta__ = PluginMetadata(
    name="打卡记鹿",
    description="你今天鹿管了ma?",
    usage="at机器人 发送：打卡    "
          "直接发送：查卡（查询打卡记录）",
    type="application",
)

record = on_command("打卡记鹿", aliases={"打卡"}, rule=to_me())
query = on_command("查询记录", aliases={"查卡"})


@record.handle()
async def do_job(bot: Bot, ev: MessageEvent):
    # 获取当前日期的年份和月份
    now = datetime.now()
    year = now.year
    month = now.month
    day = now.day
    # 获取发信人信息
    uid = str(ev.user_id)
    message_id = ev.message_id
    # 添加一条记录
    await record_month(uid, day)
    # 获取记录
    img = await draw_calendar_grid_image(uid, year, month)
    text_msg = MessageSegment.text("这是您的打卡记鹿：\n")
    image_msg = MessageSegment.image(pic2b64(img))
    mix_msg = (text_msg,)
    mix_msg += image_msg
    reply_msg = (MessageSegment.reply(message_id),)
    reply_msg += mix_msg
    await record.finish(reply_msg)


def pic2b64(pic: Image) -> str:
    buf = io.BytesIO()
    pic.save(buf, format='PNG')
    base64_str = base64.b64encode(buf.getvalue()).decode()
    return 'base64://' + base64_str


@query.handle()
async def query_job(bot: Bot, ev: MessageEvent):
    # 获取当前日期的年份和月份
    now = datetime.now()
    year = now.year
    month = now.month
    # 获取发信人信息
    uid = str(ev.user_id)
    message_id = ev.message_id
    # 获取记录
    img_file = await draw_calendar_grid_image(uid, year, month)
    text_msg = MessageSegment.text("这是您的记鹿：\n")
    image_msg = MessageSegment.image(pic2b64(img_file))
    mix_msg = (text_msg,)
    mix_msg += image_msg
    reply_msg = (MessageSegment.reply(message_id),)
    reply_msg += mix_msg
    await record.finish(reply_msg)
