import tweetnacl from 'tweetnacl';
import { useLocalStorageState } from 'ahooks';
import { useEffect } from 'react';

import { encodeKey, decrypt as _decrypt, encrypt as _encrypt } from '../../utils';

const keyPair = tweetnacl.box.keyPair();

export default function useSecurity() {
  const [encryptKey, setEncryptKey] = useLocalStorageState('__encKey', {
    defaultValue: encodeKey(keyPair.publicKey),
    deserializer: (str) => str,
    serializer: (str) => str,
  });
  const [decryptKey, setDecryptKey] = useLocalStorageState('__decKey', {
    defaultValue: encodeKey(keyPair.secretKey),
    deserializer: (str) => str,
    serializer: (str) => str,
  });

  useEffect(() => {
    if (!localStorage.getItem('__encKey')) {
      setEncryptKey(encodeKey(keyPair.publicKey));
    }
    if (!localStorage.getItem('__decKey')) {
      setDecryptKey(encodeKey(keyPair.secretKey));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const decrypt = (v, _encryptKey = encryptKey, _decryptKey = decryptKey) => _decrypt(v, _encryptKey, _decryptKey);
  const encrypt = (v, _encryptKey = encryptKey) => _encrypt(v, _encryptKey);

  return {
    encryptKey,
    decryptKey,
    decrypt,
    encrypt,
  };
}
