import {appVarActions} from '@caj/configs/appVarReducer';
import {saveVarChanges} from '@caj/helper/appData';
import {store} from '@caj/redux/store';
import {generateSecureRandom} from '@caj/encryption/secureRandom';
import {getData, setData} from '../appData';

import {Buffer} from 'buffer';

type encryptType = Uint8Array | undefined;
let dbEncryption: encryptType;

export function initKey(): Promise<Uint8Array> {
  return new Promise(async resolve => {
    let dbekIndex = store.getState().appVariables.preferences.dbek;

    if (dbekIndex === undefined || dbekIndex < 0) {
      dbekIndex = Math.round(Math.random() * 1000000);

      store.dispatch(appVarActions.setDBEK(dbekIndex));
      saveVarChanges();
    }

    let dbekEncoded = await getData('dbek' + dbekIndex);

    if (dbekEncoded === null) {
      dbEncryption = await generateSecureRandom(64);

      console.log(dbEncryption);

      let buf = Buffer.from(dbEncryption).toString('base64');

      await setData('dbek' + dbekIndex, buf);
    } else {
      dbEncryption = new Uint8Array(Buffer.from(dbekEncoded, 'base64'));
    }

    console.log('dbekIndex', dbekIndex);
    resolve(dbEncryption);
  });
}

export function getKey(): encryptType {
  return dbEncryption;
}
