var AWS = require('aws-sdk');
var mysql = require('mysql');
var EncryptionHelper = require('@sei-atl/encryption-helper');

class EnvHelper {
  constructor(context,version) {
    this.context = context;
    this.stage = this.getStage();
    this.env;
    this.version = version;
  }

  getStage() {
    if(!this.stage) {
      let parts = this.context.invokedFunctionArn.split(this.context.functionName + ":");
      this.stage = parts[1] ? parts[1] == "$LATEST" ? "DEV" : parts[1] : "DEV";
    }
    return this.stage;
  }

  getDbConnection(dbConfigPropertyName) {
    return new Promise((resolve, reject) => {
      this.getEnv()
        .then(env => {
            resolve(mysql.createConnection(env[dbConfigPropertyName || 'dbConfig']));
        }).catch(err => {
          reject(err);
        });
    });
  }

  /*
   * ENV is an AWS environment variable with the following name convetion:
   *
   * [STAGE]_ENV, for example DEV_ENV is the name of the environment variable
   * in the DEV environment.
   *
   * Furthermore, it is assumed that the environment variable is an encrypted
   * json object.
   */
  getEnv() {
    return new Promise((resolve, reject) => {
      if (this.env) {
        resolve(this.env);
      } else {
        let encrypted = this.version ? process.env.CONFIG : `${process.env[this.stage + "_ENV"]}`;
        if(encrypted) {
          EncryptionHelper
          .decrypt(encrypted)
          .then(decrypted => {
            this.env = Object.assign({}, process.env, JSON.parse(decrypted));
            resolve(this.env);
          }).catch(err => {
            reject(err);
          });
        } else {
          this.env = Object.assign({}, process.env);
          resolve(this.env);
        }
      }
    });
  }
}

module.exports = EnvHelper;
