import PublisherUtils from './publisher-utils.js'
import * as utils from '../../utils.js'
import path from 'path'
import fs from 'fs'

export default class AddDynatraceLinkPublisher {

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

  async publish(reportFilePath) {
    console.log("Running AddDynatraceLinkPublisher");
    let logStr = this.fs.readFileSync(reportFilePath, 'utf8');
    let log = JSON.parse(logStr);
    if (!logStr){
        throw new Error('Could not read logfile');
    }

    let startTime = new Date(log.allResults.start);
    let endTime = new Date(log.allResults.end);

    let extraLink = this.config.baseUrl  + "/e/" +  this.config.dynaEnvironment + "/ui/user-sessions?gtf=";
    extraLink = extraLink + startTime.toISOString();
    extraLink = extraLink + "%20to%20";
    extraLink = extraLink + endTime.toISOString();
    extraLink = extraLink + "&gf=all" + this.config.filter;

    if (!log.allResults['extraLink'] || log.allResults['extraLink'] == ""){
      log.allResults['extraLink'] = extraLink;
    } else if (Array.isArray(log.allResults['extraLink'])) {
      log.allResults['extraLink'].push(extraLink);
    } else {
      log.allResults['extraLink'] = [ log.allResults['extraLink'], extraLink];
    }

    if (log.groupedResults){
      let groups = Object.keys(log.groupedResults);
      groups.forEach(group => {
        if (!log.groupedResults[group]['extraLink'] || log.groupedResults[group]['extraLink'] == ""){
          log.groupedResults[group]['extraLink'] = extraLink;
        } else if (Array.isArray(log.groupedResults[group]['extraLink'])) {
          log.groupedResults[group]['extraLink'].push(extraLink);
        } else {
          log.groupedResults[group]['extraLink'] = [log.groupedResults[group]['extraLink'], extraLink];
        }
      });
    }

    log.allResults.describes.forEach(describe => {
      let startTime = new Date(describe.start);
      let endTime = new Date(describe.end);

      extraLink = this.config.baseUrl  + "/e/" +  this.config.dynaEnvironment + "/ui/user-sessions?gtf=";
      extraLink = extraLink + startTime.toISOString();
      extraLink = extraLink + "%20to%20";
      extraLink = extraLink + endTime.toISOString();
      extraLink = extraLink + "&gf=all" + this.config.filter;

      if (!describe['extraLink'] || describe['extraLink'] == ""){
        describe['extraLink'] = extraLink;
      } else if (Array.isArray(describe['extraLink'])) {
        describe['extraLink'].push(extraLink);
      } else {
        describe['extraLink'] = [ describe['extraLink'], extraLink];
      }
    });

    this.fs.writeFileSync(reportFilePath,
      JSON.stringify(log,null,2), function(err) {
            if (err) {
                return console.error("Error writing updated logfile in AddDynatraceLinkPublisher: " + err);
            }
        }
    );
  }
}
