package com.grkj.iscs.ble;

/**
 * 蓝牙 章节 4.1
 */
public class KeyGenerator {
    private static final int[] PASSWORD_ARRAY = {
            0x1D83, 0x0E52, 0xAF42, 0x3072, 0x7D8C, 0xC0EC, 0xBD93, 0x3258,
            0x95DD, 0x5D28, 0xCE35, 0x59AA, 0xDEC0, 0xCFD1, 0x2F36, 0x8DAA,
            0xC910, 0x5DE8, 0x0AC6, 0x8C46, 0xD98B, 0x33D2, 0x3C43, 0x12E0,
            0x25FC, 0xCC82, 0x1158, 0xB585, 0x6616, 0x621D, 0xF02F, 0xA136,
            0x3614, 0x3C5C, 0x68DF, 0x5C26, 0x9ACC, 0x5D80, 0xEB45, 0x2AC8,
            0xD1FC, 0x992D, 0x8DC5, 0x91F0, 0x70F5, 0x5C32, 0xC8BD, 0xE750,
            0x69FC, 0x67BD, 0x89FB, 0xD298, 0x5CC2, 0xBE27, 0x5C5C, 0xAE6B,
            0x03F5, 0x7C23, 0xB6AA, 0x0999, 0x6D5E, 0x5F89, 0x2A1C, 0xD3F7
    };

    public static byte[] generateKey(byte[] macAddress, long token) {
        byte[] key = new byte[16];

        // Step 1: Calculate remainder of each byte of the MAC address with 64.
        int[] remainders = new int[6];
        for (int i = 0; i < 6; i++) {
            remainders[i] = macAddress[i] & 0xFF;
            remainders[i] %= 64;
        }

        // Step 2: Use each result as index to fetch 6 values from PASSWORD_ARRAY.
        for (int i = 0; i < 6; i++) {
            System.arraycopy(intToBytes(PASSWORD_ARRAY[remainders[i]]), 2, key, i * 2, 2);
        }

        // Steps 3-6: Extract bytes from token and place them in the key array.
        key[12] = (byte)((token >> 24) & 0xFF);
        key[13] = (byte)((token >> 16) & 0xFF);
        key[14] = (byte)((token >> 8) & 0xFF);
        key[15] = (byte)(token & 0xFF);

        return key;
    }

    private static byte[] intToBytes(int value) {
        return new byte[]{
                (byte) (value >>> 24),
                (byte) (value >>> 16),
                (byte) (value >>> 8),
                (byte) value
        };
    }
}
