var AWS = require('aws-sdk');
const crypto = require('crypto');
if (!AWS.config.region) {
  AWS.config.update({
    region: 'us-east-1'
  });
}
let EncryptionHelper = {
  AES_256_CBC: 'aes-256-cbc',

  base64Encode: (str) => {
    return new Buffer(str, 'base64');
  },

  base64Decode: (buffer) => {
    return buffer.toString('base64');
  },

  encrypt: (str, keyId) => {
    return new Promise((resolve, reject) => {
      const kms = new AWS.KMS();
      var params = {
        KeyId: keyId,
        Plaintext: str
      };
      kms.encrypt(params, function(err, encrypted) {
        if (err) {
          console.log('Encryption Error: ', err, err.stack);
          reject(err);
        } else {
          resolve(encrypted);           // successful response
        }
      });
    });
  },

  decrypt: (encrypted) => {
    return new Promise((resolve, reject) => {
      const kms = new AWS.KMS();
      kms.decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') }, (err, data) => {
        if (err) {
          console.log('Decryption error:', err);
          reject(err);
        }
        let decrypted = data.Plaintext.toString('ascii');
        resolve(decrypted);
      });
    });
  },

  encryptAes256Cbc: (plainText, key) => {
    return new Promise((resolve, reject) => {
      try {
        if(!key) {
          key = crypto.randomBytes(32);
        } else {
          key = key.toLowerCase().replace(/[^a-z0-9]/g, '');
        }
        const iv = crypto.randomBytes(16);
        let cipher = crypto.createCipheriv(EncryptionHelper.AES_256_CBC, Buffer.from(key), iv);
        let encrypted = cipher.update(plainText);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        resolve({
          iv: iv.toString('hex'),
          encryptedData: encrypted.toString('hex') 
        });
      } catch(err) {
        reject(err);
      }
    });
  },

  decryptAes256Cbc: (encrypted, key) => {
    return new Promise((resolve, reject) => {
      key = key ? key.toLowerCase().replace(/[^a-z0-9]/g, '') : null;
      try {
        let iv = Buffer.from(encrypted.iv, 'hex');
        let encryptedText = Buffer.from(encrypted.encryptedData, 'hex');
        let decipher = crypto.createDecipheriv(EncryptionHelper.AES_256_CBC, Buffer.from(key), iv);
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        resolve(decrypted.toString());
      } catch (err) {
        reject(err);
      }
    });
  }
}

// EncryptionHelper.decrypt('AQICAHiz6cK5HJTtT5UgqQ2+gKVF9c/sFDAAp7xOJnTGyGUFywF0Oq2lmQ4nznm8D6lu9T7NAAAA3TCB2gYJKoZIhvcNAQcGoIHMMIHJAgEAMIHDBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDK13Huo3v+oFG3qeXgIBEICBlU4S6C3BkHY2B5+h8mmOQ7SiQDIJ8CSFjdJcs5kTbJlCcF38A6PbUuggPiSbnsrFTJimCDr6G+oV8qw7r/rbPD7TWunB1r4qgNBp7EPHrTYW6JFvt0Yhgsn9aCMiGow6e6LgOD22eTwEi0YEbjU4QZ/OWbDkRta6th3m9eGkDnSIl304xdqrTwPylLHRUL/PzzFQkPpd')
// .then(decrypted => {
//   console.log('decrypted', decrypted);
// });


// EncryptionHelper.encrypt('{"elastiCacheUrl":"//prod-ccna-tis.bfx2cs.ng.0001.use1.cache.amazonaws.com:6379","dryBlendId":"01261000000MFLXAA4"}', 'cb7c588c-d840-44ce-8b9d-77e3913ef9cf')
// .then(encrypted => {
//   console.log('encrypted', EncryptionHelper.base64Decode(encrypted.CiphertextBlob));
// });


module.exports = EncryptionHelper;
