import qrcode
# from pyzbar.pyzbar import decode
# from PIL import Image
import requests
from io import BytesIO

from nonebot_plugin_alconna import (Alconna, Args, Field, MultiVar, UniMessage,
                                    on_alconna)
from nonebot_plugin_alconna.uniseg import UniMsg, At, Reply

from konabot.common.nb.wzq_conflict import no_wzqbot_rule

async def download_img(url):
    resp = requests.get(url.replace("https://multimedia.nt.qq","http://multimedia.nt.qq")) # bim获取QQ的图片时避免SSLv3报错
    img_bytes = BytesIO()
    with open(img_bytes,"wb") as f:
        f.write(resp.content)
    return img_bytes

def genqr(data):
    qr = qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=8,border=4)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    img_bytes = BytesIO()
    img.save(img_bytes, format="PNG")
    return img_bytes

"""
async def recqr(url):
    im_path = "assets/img/qrcode/2.jpg"
    data = await download_img(url)
    img = Image.open(im_path)
    decoded_objects = decode(img)
    data = ""
    for obj in decoded_objects:
        data += obj.data.decode('utf-8')
    return data
"""

gqrc = on_alconna(Alconna(
    "genqr",
    Args["saying", MultiVar(str, '+'), Field(
        missing_tips=lambda: "请输入你要转换为二维码的文字！"
    )],
    # UniMessage[]
), use_cmd_start=True, use_cmd_sep=False, skip_for_unmatch=False, aliases={"生成二维码","genqrcode"}, rule=no_wzqbot_rule)

@gqrc.handle()
async def _(saying: list):
    """
    img = await draw_pt("\n".join(saying))
    img_bytes = BytesIO()
    img.save(img_bytes, format="PNG")

    await pt.send(await UniMessage().image(raw=img_bytes).export())
    
    # print(saying)
    # 二维码识别
    if type(saying[0]) == 'image':
        data = await recqr(saying[0].data['url'])
        if data == "":
            await gqrc.send("二维码图片解析失败！")
        else:
            await gqrc.send(recqr(saying[0].data['url']))
    
    # 二维码生成
    else:
    """
        # genqr("\n".join(saying))
    await gqrc.send(await UniMessage().image(raw=genqr("\n".join(saying))).export())
