

import { ShareConfig } from './ShareConfig';
// import TextEncodingPolyfill from 'text-encoding';
/** 数据传输加密 */
export class Security {

    static repeatArray(arr: Array<number>, size: number): Array<number> {
        let repeatedArray = arr.slice(); // 复制原数组
        while (repeatedArray.length < size) {
            // 如果数组长度小于指定大小，就复制一份原数组内容并追加到末尾
            repeatedArray = repeatedArray.concat(arr.slice(0, size - repeatedArray.length));
        }
        return repeatedArray.slice(0, size); // 返回指定长度的数组
    }

    static mapKey(size: number): Array<number> {

        const seed = Number('905010410038421001031011063552115');
        // const seed = Number(new TextEncodingPolyfill.TextEncoder().encode(ShareConfig.securityKey).join(''));
        const dict = new Array(256);

        for (let i = 0; i < 256; i++) {
            const temp = dict[i] || i;
            const rand = (seed % (i + 1) + i) % 256;
            dict[i] = dict[rand] || rand;
            dict[rand] = temp;
        }

        if (size > 256) {
            return Security.repeatArray(dict, size);
        } else {
            return dict;
        }
    }

    static byteIn(keyMap: Array<number>, val: number, index: number): number {
        for (let i = 0; i < keyMap.length; i++) {
            if (keyMap[i] === val) return (i + keyMap[index]) % 256;
        }
        return 0;
    }

    static byteOut(keyMap: Array<number>, val: number, index: number): number {
        const diff = val - keyMap[index];
        return keyMap[(diff < 0) ? 256 + diff : diff];
    }

    /** 加密 */
    static encrypt(buf: Uint8Array): Uint8Array {
        return buf.map(Security.byteIn.bind(null, Security.mapKey(buf.length)));
    }

    /** 解密 */
    static decrypt(buf: Uint8Array): Uint8Array {
        return buf.map(Security.byteOut.bind(null, Security.mapKey(buf.length)));
    }
}