package com.wzj.soopin.im.util;


import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Deflater;

public class TLSSigAPIv2 {
    private static long sdkappid = 1600080789; // 替换为您的 SDKAppID

    private static String key = "311b5309d714a20f7f5b54360ee21b1e24ec208ebcd25ce8f47d24753bccc091"; // 替换为您的密钥

    public TLSSigAPIv2(long sdkappid, String key) {
        this.sdkappid = sdkappid;
        this.key = key;
    }

    /**
     * 生成 UserSig 签名
     *
     * @param userid - 用户id，限制长度为32字节，只允许包含大小写英文字母（a-zA-Z）、数字（0-9）及下划线和连词符
     * @param expire - UserSig 票据的过期时间，单位是秒，比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了
     * @return usersig - 生成的签名
     */
    public String genUserSig(String userid, long expire) {
        return genUserSig(userid, expire, null);
    }

    /**
     * 生成带 UserBuf 的 UserSig
     *
     * @param userid - 用户id
     * @param expire - 过期时间，单位秒
     * @param userbuf - 用户数据
     * @return 生成的签名
     */
    private String genUserSig(String userid, long expire, byte[] userbuf) {
        long currTime = System.currentTimeMillis() / 1000;

        JSONObject sigDoc = new JSONObject();
        try {
            sigDoc.put("TLS.ver", "2.0");
            sigDoc.put("TLS.identifier", userid);
            sigDoc.put("TLS.sdkappid", sdkappid);
            sigDoc.put("TLS.expire", expire);
            sigDoc.put("TLS.time", currTime);

            String base64UserBuf = null;
            if (null != userbuf) {
                base64UserBuf = Base64.getEncoder().encodeToString(userbuf).replaceAll("\\s*", "");
                sigDoc.put("TLS.userbuf", base64UserBuf);
            }

            String sig = hmacsha256(userid, currTime, expire, base64UserBuf);
            if (sig.length() == 0) {
                return "";
            }
            sigDoc.put("TLS.sig", sig);

            Deflater compressor = new Deflater();
            compressor.setInput(sigDoc.toString().getBytes(StandardCharsets.UTF_8));
            compressor.finish();
            byte[] compressedBytes = new byte[2048];
            int compressedBytesLength = compressor.deflate(compressedBytes);
            compressor.end();

            return Base64.getEncoder().encodeToString(
                    Arrays.copyOfRange(compressedBytes, 0, compressedBytesLength)
            ).replaceAll("\\s*", "");

        } catch (JSONException e) {
            return "";
        }
    }

    /**
     * 生成 PrivateMapKey
     */
    public String genPrivateMapKey(String userid, long expire, long roomid, long privilegeMap) {
        byte[] userbuf = genUserBuf(userid, roomid, expire, privilegeMap, 0, "");
        return genUserSig(userid, expire, userbuf);
    }

    /**
     * 生成带字符串房间号的 PrivateMapKey
     */
    public String genPrivateMapKeyWithStringRoomID(String userid, long expire, String roomstr, long privilegeMap) {
        byte[] userbuf = genUserBuf(userid, 0, expire, privilegeMap, 0, roomstr);
        return genUserSig(userid, expire, userbuf);
    }

    /**
     * 生成 HMAC-SHA256 签名
     */
    private String hmacsha256(String identifier, long currTime, long expire, String base64Userbuf) {
        String contentToBeSigned = "TLS.identifier:" + identifier + "\n"
                + "TLS.sdkappid:" + sdkappid + "\n"
                + "TLS.time:" + currTime + "\n"
                + "TLS.expire:" + expire + "\n";
        if (null != base64Userbuf) {
            contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n";
        }

        try {
            byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256");
            hmac.init(keySpec);
            byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(byteSig).replaceAll("\\s*", "");
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            return "";
        }
    }

    /**
     * 生成用户数据
     */
    private byte[] genUserBuf(String account, long dwAuthID, long dwExpTime,
                              long dwPrivilegeMap, long dwAccountType, String roomStr) {
        int accountLength = account.length();
        int roomStrLength = roomStr.length();
        int offset = 0;
        int bufLength = 1 + 2 + accountLength + 20;

        if (roomStrLength > 0) {
            bufLength = bufLength + 2 + roomStrLength;
        }

        byte[] userbuf = new byte[bufLength];

        // 版本号
        userbuf[offset++] = (byte)(roomStrLength > 0 ? 1 : 0);

        // 账号长度
        userbuf[offset++] = (byte) ((accountLength & 0xFF00) >> 8);
        userbuf[offset++] = (byte) (accountLength & 0x00FF);

        // 写入账号
        for (; offset < 3 + accountLength; ++offset) {
            userbuf[offset] = (byte) account.charAt(offset - 3);
        }

        // 写入 sdkappid
        userbuf[offset++] = (byte) ((sdkappid & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((sdkappid & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((sdkappid & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (sdkappid & 0x000000FF);

        // 写入房间号
        userbuf[offset++] = (byte) ((dwAuthID & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwAuthID & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwAuthID & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwAuthID & 0x000000FF);

        // 过期时间
        long expire = System.currentTimeMillis() / 1000 + dwExpTime;
        userbuf[offset++] = (byte) ((expire & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((expire & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((expire & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (expire & 0x000000FF);

        // 权限位
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwPrivilegeMap & 0x000000FF);

        // 账号类型
        userbuf[offset++] = (byte) ((dwAccountType & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwAccountType & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwAccountType & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwAccountType & 0x000000FF);

        // 房间号字符串
        if (roomStrLength > 0) {
            userbuf[offset++] = (byte) ((roomStrLength & 0xFF00) >> 8);
            userbuf[offset++] = (byte) (roomStrLength & 0x00FF);
            for (; offset < bufLength; ++offset) {
                userbuf[offset] = (byte) roomStr.charAt(offset - (bufLength - roomStrLength));
            }
        }

        return userbuf;
    }
}
