import base64

import pyotp
import os
import traceback
from qrcode import QRCode, constants
from six import BytesIO


def get_qrcode(username: str, gtoken: str):
    # gtoken = pyotp.random_base32(64)
    # dirpath = os.path.join(os.getcwd())
    data = pyotp.totp.TOTP(gtoken).provisioning_uri(username, issuer_name="IAM MFA Code")
    qr = QRCode(
        version=1,
        error_correction=constants.ERROR_CORRECT_L,
        box_size=6,
        border=4, )
    try:
        qr.add_data(data)
        qr.make(fit=True)
        img = qr.make_image()
        # filepath = dirpath + os.sep + username + '.png'
        # img.save(filepath)  # 保存条形码图片
        # 图片以二进制形式写入
        buf = BytesIO()
        img.save(buf, 'jpeg')
        buf_str = buf.getvalue()
        img_b = b"data:image/png;base64," + base64.b64encode(buf_str)
        return img_b
    except Exception as e:
        traceback.print_exc()
        return False


def google_verify_result(secret_key, google_code):
    """谷歌动态码效验"""
    t = pyotp.TOTP(secret_key)
    result = t.verify(google_code)  # 对输入验证码进行校验，正确返回True
    msg = result if result is True else False
    return msg