import cryptoJs from 'crypto-js'

const key = 'WB0nMZHXlxNndORe'
const keyHex = cryptoJs.enc.Utf8.parse(key)

function cryptoSecureRandomInt() {
    if (crypto) {
        // Use getRandomValues method (Browser)
        if (typeof crypto.getRandomValues === 'function') {
            try {
                return crypto.getRandomValues(new Uint32Array(1))[0];
            } catch (err) {}
    } // Use randomBytes method (NodeJS)


    if (typeof crypto.randomBytes === 'function') {
        try {
            return crypto.randomBytes(4).readInt32LE();
        } catch (err) {}
        }
    }

    throw new Error('Native crypto module could not be used to get secure random number.');
  }

export const encrypt = (data) => {
//	#ifndef APP-NVUE
  const iv = cryptoJs.lib.WordArray.random(16)
// #endif
// #ifdef APP-NVUE
  var words = [];
  for (var i = 0; i < 16; i += 4) {
    words.push(cryptoSecureRandomInt());
  }
  const iv = new cryptoJs.lib.WordArray.init(words, 16)
//#endif
  const dataHex = cryptoJs.enc.Utf8.parse(
    typeof data === 'string' ? data : JSON.stringify(data)
  )
  const encrypted = cryptoJs.AES.encrypt(dataHex, keyHex, {
    iv: iv,
    mode: cryptoJs.mode.CFB,
    padding: cryptoJs.pad.NoPadding,
  }).ciphertext.toString(cryptoJs.enc.Hex)
  return (
    encrypted.substring(0, 16) +
    cryptoJs.enc.Hex.stringify(iv) +
    encrypted.substring(16)
  )
}

export const decrypt = (value) => {
  const len = value.length
  let part1 = '',
      part2 = '',
      iv = ''
  if (len < 48) {
    part1 = value.substring(0, len-32)
    iv = value.substring(len-32)
  } else {
    part1 = value.substring(0, 16)
    part2 = value.substring(48)
    iv = value.substring(16, 48)
  }
  let encryptedHexStr = cryptoJs.enc.Hex.parse(part1 + part2)
  let src = cryptoJs.enc.Base64.stringify(encryptedHexStr)
  const keyHex = cryptoJs.enc.Utf8.parse(key)
  const ivHex = cryptoJs.enc.Hex.parse(iv)
  let decrypt = cryptoJs.AES.decrypt(src, keyHex, {
    iv: ivHex,
    mode: cryptoJs.mode.CFB,
    padding: cryptoJs.pad.NoPadding,
  })
  return JSON.parse(decrypt.toString(cryptoJs.enc.Utf8))
}
