package com.crm.rely.backend.util;

import com.google.common.base.Strings;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator;

/**
 * @Author houn
 * @Date 2024/12/3 17:24
 * @PackageName:com.crm.rely.backend.util
 * @ClassName: GoogleAuthenticatorUtil
 * @Description: TODO
 */
public class GoogleAuthenticatorUtil {

    private final static String DEFAULT_ISSUER = "GOOGLE";

    public static void main(String[] args) {
        String secretKey = generateSecretKey();
        System.out.println(secretKey);
        System.out.println(getOtpAuthURL(secretKey));

//
//        String secretKey = "5FC5O2Z4ESVWPAXWPGOZM5KZMTZPHNE4";
//        System.out.println(verifyCode(secretKey, 111111));
    }

    /**
     * 生成 Google Authenticator 应用的二维码 URL
     *
     * @param secretKey
     * @return
     */
    public static String getOtpAuthURL(String secretKey) {

        return getOtpAuthURL(secretKey, null);
    }

    /**
     * 生成 Google Authenticator 应用的二维码 URL
     *
     * @param secretKey
     * @param accountName
     * @return
     */
    public static String getOtpAuthURL(String secretKey, String accountName) {

        return getOtpAuthURL(secretKey, accountName, null);
    }

    /**
     * 生成 Google Authenticator 应用的二维码 URL
     *
     * @param secretKey
     * @param accountName
     * @param issuer
     * @return
     */
    public static String getOtpAuthURL(String secretKey, String accountName, String issuer) {

        if (Strings.isNullOrEmpty(accountName)) {
            accountName = DEFAULT_ISSUER;
        }

        GoogleAuthenticatorKey key = createGoogleAuthenticatorKey(secretKey);

        // 生成 Google Authenticator 应用的二维码 URL
        String qrCodeUrl = GoogleAuthenticatorQRGenerator.getOtpAuthURL(issuer, accountName, key);

        return qrCodeUrl;
    }

    /**
     * 生成用户的 Google Authenticator 密钥
     */
    public static String generateSecretKey() {


        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        GoogleAuthenticatorKey key = gAuth.createCredentials();

        // 将密钥保存到用户账户（数据库或其他存储）
        String secretKey = key.getKey();

        return secretKey;
    }

    /**
     * 根据已有的 secretKey 生成 GoogleAuthenticatorKey
     *
     * @param secretKey
     * @return
     */
    public static GoogleAuthenticatorKey createGoogleAuthenticatorKey(String secretKey) {
        return new GoogleAuthenticatorKey.Builder(secretKey).build();
    }

    /**
     * 验证绑定时的 Google Authenticator 动态验证码
     *
     * @param secretKey
     * @param verificationCode
     * @return
     */
    public static boolean verifyCode(String secretKey, int verificationCode) {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        return gAuth.authorize(secretKey, verificationCode);
    }
}
