import VaultService from '../services/vault-service.js';
import superagent from 'superagent';

export default class CamundaProcessLauncher {

  constructor(config) {
    this.request = superagent;
    this.config = config;
    this.authToken = false;
  }

  async startProcess(processJson) {
    try {
      if (!this.authToken) {
        await this.auth();
      }
      let response;
      response = await this.request
        .post(this.config.camundaProcessLauncher.url + processJson.processType + '/start-process-instance')
        .set('content-type', 'application/json')
        .set('Authorization', 'Bearer ' + this.authToken)
        .set('Authorization-Propagation', this.authToken)
        .type('json')
        .send(processJson.body);

      if (response.statusCode === 200) {
        console.dir('The process with processTypeKey ' + processJson.processType + ' was launched.');
      } else {
        throw new Error('The process with processTypeKey ' +
          processJson.processType + ' cannot be launched.');
      }
    } catch (error) {
      throw new Error('Error on Camunda Process Launcher: ' + error);
    }
  }

  async auth() {
    try {
      let vault = new VaultService(this.config);

      let secrets = await vault.getSecret(this.config.camundaProcessLauncher.auth.vault_path, this.config.camundaProcessLauncher.auth.vault_key);
      let userPasswordBase64 = Buffer.from(secrets[this.config.camundaProcessLauncher.auth.vault_key].client_id + ':'
        + secrets[this.config.camundaProcessLauncher.auth.vault_key].client_secret, 'utf-8').toString('base64');

      let response = await this.request
        .post(this.config.camundaProcessLauncher.auth.url)
        .set('Authorization', 'Basic ' + userPasswordBase64)
        .send(this.config.camundaProcessLauncher.auth.body);

      if (response.body.access_token) {
        this.authToken = String(response.body.access_token);
      } else {
        throw new Error('Cannot identify the access_token in the response: ' + response.body);
      }
    } catch (error) {
      throw new Error('Cannot authenticate to API Gateway. ' + error);
    }
  }
}
