import fs from 'fs'
import path from 'path'
import superagent from 'superagent'
export default class BambooEsPublisherTrigger {

  constructor( config ) {
    this.fs = fs;
    this.path = path;
    this.config = config;
    this.request = superagent;
  }

  async publish(reportFilePath) {
    try {
      let logStr = this.fs.readFileSync(reportFilePath, 'utf8');
      if (!logStr){
        throw new Error('Could not read logfile');
      }

      this.log = JSON.parse(logStr);
      if (!this.log.jsonLink){
        throw new Error("Log doesn't contain jsonLink");
      }
      if (!this.config.esConfig){
        throw new Error("esConfig does not exist in the BambooEsPublisherTrigger config");
      }

      this.config.esConfig["jsonLink"] = this.log.jsonLink;

      let response = await this.request
      .post(this.config.bambooUrl + "/rest/api/latest/queue/" + this.config.buildKey)
      .send("bamboo.variable.CONFIG=" +  JSON.stringify(this.config.esConfig))
      .set('Authorization', "Bearer " + this.config.bambooToken );
    } catch (error) {
      console.error('An error occured in BambooEsPublisherTrigger.publish, error:' + error);
      return;
    }
  }
}
