using System;
using UnityEngine;
public class BluetoothDecryptor
{
    // 授权标志
    private static bool _authorizationFlg = false;
    // 密钥长度
    private const int KEY_LENGTH = 12;
    // 对称密钥
    private static readonly byte[] c_abySecretKey = System.Text.Encoding.ASCII.GetBytes("qingfengluan");
    private static readonly byte[] _decryptExpected = new byte[4];
    private static readonly byte[] _encryptExpected = new byte[4];
    /***********************************************************
      *@函 数 名	:	AUTHOR_ImprovedEncrypt
      *@功能说明	:	加密函数
      *@形    参	:	pbyData - 待加密字符串
      *@				dwDataLen - 加密数据长度
      *@返 回 值	:	void
      *@作    者	:	Shaoxin Wu
      *@日    期	:	2024-06-24
    ***********************************************************/
    private static void AUTHOR_ImprovedEncrypt(byte[] data, int offset, int length)
    {
        for (int i = offset; i < offset + length; i++)
        {
            for (int j = 0; j < KEY_LENGTH; j++)
            {
                data[i] ^= c_abySecretKey[j]; // 多轮异或
                data[i] = (byte)((data[i] << 1) | (data[i] >> 7)); // 左循环移位
            }
        }
    }
    /***********************************************************
    *@函 数 名 : AUTHOR_ImprovedDecrypt
    *@功能说明 : 解密函数
    *@形 参 : pbyData - 待解密字符串
    *@ dwDataLen - 解密数据长度
    *@返 回 值 : pbyData - 解密后的数据
    *@作 者 : Shaoxin Wu
    *@日 期 : 2024-06-24
    ***********************************************************/
    public static byte[] AUTHOR_ImprovedDecrypt(byte[] pbyData, uint dwDataLen)
    {
        for (uint i = 0; i < dwDataLen; i++)
        {
            for (int j = KEY_LENGTH - 1; j >= 0; j--)
            {
                pbyData[i] = (byte)((pbyData[i] >> 1) | (pbyData[i] << 7)); // 右循环移位
                pbyData[i] ^= c_abySecretKey[j]; // 多轮异或
            }
        }
        return pbyData;
    }
    /***********************************************************
    *@函 数 名 : CheckSum
    *@功能说明 : 累加和校验计算
    *@形 参 : pbyData - 数据地址
    *@ byDataLen - 校验数据长度
    *@返 回 值 : 校验和结果
    *@作 者 : Shaoxin Wu
    *@日 期 : 2024-06-24
    ***********************************************************/
    public static byte CheckSum(byte[] pbyData, byte byDataLen)
    {
        byte byRet = 0;
        for (byte i = 0; i < byDataLen; i++)
        {
            byRet += pbyData[i];
        }
        return byRet;
    }
    /// 
    /// 最前面插入一个字节
    /// 
    /// 
    /// 
    /// 
    public static byte[] InsertByteAtBeginning(byte[] originalArray, byte newByte)
    {
        byte[] newArray = new byte[originalArray.Length + 1];
        newArray[0] = newByte;
        Array.Copy(originalArray, 0, newArray, 1, originalArray.Length);
        return newArray;
    }
    public static byte[] GetResponse(byte[] bytes) {
        //byte[] dataToDecrypt = { 0x5A, 0x76, 0xD1, 0x02, 0xEB, 0x8E, 0x5D };
        //需要解密的4个数据
        byte[] encryptedData = new byte[] { bytes[1], bytes[2], bytes[3], bytes[4] };
        uint dataLength = (uint)encryptedData.Length;
        byte checksumStart = CheckSum(new byte[] { bytes[0] , bytes[1], bytes[2], bytes[3], bytes[4] }, 5);
        // 打印开始校验和
        //Debug.Log("checksumStart: " + checksumStart + ",对应16进制=" + checksumStart.ToString("X"));
        // 打印原始加密数据
        Debug.Log("Original Data: " + System.BitConverter.ToString(bytes));
        //Debug.Log("Original Encrypted Data: " + System.BitConverter.ToString(encryptedData));
        // 解密数据
        byte[] decryptedData = AUTHOR_ImprovedDecrypt(encryptedData, dataLength);
        // 打印解密后的数据
        //Debug.Log("Decrypted Data: " + System.BitConverter.ToString(decryptedData));
        byte[] newArray = InsertByteAtBeginning(decryptedData, bytes[0]);
        //Debug.Log("前插 {0x5A} 后:  " + System.BitConverter.ToString(newArray));
        // 计算累加和校验
        byte checksum = CheckSum(newArray, (byte)newArray.Length);
       // Debug.Log("checksum:" + checksum + ", 对应16进制:"+ checksum.ToString("X"));
        //byte checksum = Decryptor.CheckSum(decryptedData, (byte)dataLength);
        //// 打印校验和
        //Debug.Log("Checksum: " + checksum+",16=" + checksum.ToString("X"));
        // 组装应答数据
        byte[] responseData = new byte[7];
        responseData[0] = 0x5A; // 起始码
        System.Array.Copy(decryptedData, 0, responseData, 1, decryptedData.Length); // 解密数据
        responseData[5] = checksum; // 累加和校验
        responseData[6] = 0x5D; // 结束码
        // 将应答数据转换为字符串
        Debug.Log("Original Response Data: " + System.BitConverter.ToString(responseData));
       // string responseString = System.BitConverter.ToString(responseData).Replace("-", "");
        //Debug.Log("Response Data: " + responseString);
        return responseData;
    }
    /***********************************************************
   *@函 数 名	:	AUTHOR_GenerateRandomData
   *@功能说明	:	生成随机数据函数
   *@形    参	:	dwSeed - 种子值
   *@				pbyData - 存放随机数据的数组
   *@				dwDataLen - 随机数据长度
   *@返 回 值	:	void
   *@作    者	:	Shaoxin Wu
   *@日    期	:	2024-06-24
   ***********************************************************/
    private static void AUTHOR_GenerateRandomData(uint dwSeed, byte[] data, int offset, int length)
    {
        for (int i = 0; i < length; i++)
        {
            data[offset + i] = (byte)(dwSeed & 0xFF); // 简单地取低8位作为随机数据
            dwSeed >>= 1; // 移位
        }
    }
    /***********************************************************
    *@函 数 名	:	AUTHOR_IsDecrypt
    *@功能说明	:	获取授权状态
    *@形    参	:	void
    *@返 回 值	:	void
    *@作    者	:	Shaoxin Wu
    *@日    期	:	2024-07-28
    ***********************************************************/
    public static bool AUTHOR_IsDecrypt()
    {
        return _authorizationFlg;
    }
    /***********************************************************
    *@函 数 名	:	AUTHOR_Decrypt
    *@功能说明	:	解析授权响应数据
    *@形    参	:	void
    *@返 回 值	:	void
    *@作    者	:	Shaoxin Wu
    *@日    期	:	2024-07-28
    ***********************************************************/
    public static void AUTHOR_Decrypt(byte[] pbyData)
    {
        byte byCheckSum = CheckSum(pbyData, 5);
        if (byCheckSum == pbyData[5])
        {
            Array.Copy(pbyData, 1, _encryptExpected, 0, 4);
            if (BitConverter.ToUInt32(pbyData, 1) == BitConverter.ToUInt32(_decryptExpected, 0))
            {
                _authorizationFlg = true;
            }
        }
    }
    /***********************************************************
    *@函 数 名	:	AUTHOR_Encryption
    *@功能说明	:	取消授权
    *@形    参	:	void
    *@返 回 值	:	void
    *@作    者	:	Shaoxin Wu
    *@日    期	:	2024-07-28
    ***********************************************************/
    public static void AUTHOR_Encryption()
    {
        _authorizationFlg = false;
    }
    /***********************************************************
    *@函 数 名	:	AUTHOR_SendReq
    *@功能说明	:	输入系统Tick,生成随机值并加密
    *@形    参	:	void
    *@返 回 值	:	void
    *@作    者	:	Shaoxin Wu
    *@日    期	:	2024-07-28
    ***********************************************************/
    public static byte[] AUTHOR_SendReq(uint dwTick)
    {
        byte[] abySendData = new byte[7];
        abySendData[0] = 0x5A;
        // 根据种子生成随机值
        AUTHOR_GenerateRandomData(dwTick, abySendData, 1, 4);
        Array.Copy(abySendData, 1, _decryptExpected, 0, 4);
        // 加密数据
        AUTHOR_ImprovedEncrypt(abySendData, 1, 4);
        abySendData[5] = CheckSum(abySendData, 5);
        abySendData[6] = 0x5D;
        return abySendData;
    }
    //// 模拟发送数据
    //private static void SPP_DataNotify(byte[] data)
    //{
    //    // 实际发送数据的实现
    //    Console.WriteLine(BitConverter.ToString(data));
    //}
}