import { Injectable } from '@nestjs/common';
import * as CryptoJS from 'crypto-js';


@Injectable()
export class CryptoService {
  constructor() { }

  //The set method is use for encrypt the value.
  set(keys, value) {
    var key = CryptoJS.enc.Utf8.parse(keys);
    var iv = CryptoJS.enc.Utf8.parse(keys);
    var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value.toString()), key,
      {
        keySize: 128 / 8,
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });

    return encrypted.toString();
  }

  //The get method is used for decrypt the value.
  get(keys, value) {
    var key = CryptoJS.enc.Utf8.parse(keys);
    var iv = CryptoJS.enc.Utf8.parse(keys);
    var decrypted = CryptoJS.AES.decrypt(value, key, {
      keySize: 128 / 8,
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });

    return decrypted.toString(CryptoJS.enc.Utf8);
  }

  //encryption method
  encryptAesB64(value) {
    let b64 = CryptoJS.AES.encrypt(value.toString(), 'etarucca').toString();
    let e64 = CryptoJS.enc.Base64.parse(b64);
    let encryptedCode = e64.toString(CryptoJS.enc.Hex);
    return { "data": encryptedCode };
  }

  //decryption method
  decryptAesB64(value) {
    var reb64 = CryptoJS.enc.Hex.parse(value);
    var bytes = reb64.toString(CryptoJS.enc.Base64);
    var decrypt = CryptoJS.AES.decrypt(bytes, 'etarucca');
    var dycryptedCode = decrypt.toString(CryptoJS.enc.Utf8);
    return dycryptedCode
  }

}