import fs from 'fs'
import JiraService from '../../services/jira-service.js';
import utils from './publisher-utils.js'
export default class JiraCommentPublisher {

    constructor( config ) {
        this.fs = fs;
        
        this.utils = utils;
        this.jira = new JiraService(config);
        this.config = config;
    }

    async publish(reportFilePath) {
      try {
          let logStr = this.fs.readFileSync(reportFilePath, 'utf8');
          if (!logStr){
              throw new Error('Could not read logfile');
          }
          let log = JSON.parse(logStr);
          if (!log.allResults.meta || !log.allResults.meta.env){
            throw new Error('Logfile is missing data');
          }
          let issueKey = "";
          if (this.config.issueKey){
            issueKey = this.config.issueKey;
          } else if ( log.allResults.meta.jiraissuekey ){
            issueKey = log.allResults.meta.jiraissuekey;
          } else {
            throw new Error('Jira Issue Key to post commnet not set');
          }

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

          let comment = "Finished test on app";
          if (log.allResults.meta.app) {
            comment = comment + " " + log.allResults.meta.app;
          }
          if (log.allResults.meta.app) {
            comment = comment + " with URL: " + log.allResults.meta.baseUrl;
          }
          if (log.allResults.meta.testedVersion) {
            comment = comment + "\nVersion: " + log.allResults.meta.testedVersion;
          }
          if (log.allResults.meta.env) {
            comment = comment + "\nEnvironment: " + log.allResults.meta.env;
          }
          if (log.allResults.meta.suite) {
            comment = comment + "\nTested Suite: " + log.allResults.meta.suite;
          }
          if (log.allResults.meta.config_file) {
            comment = comment + "\nTest config file: " + log.allResults.meta.config_file;
          }
          comment = comment + "\nTest start time: " + startTime;
          comment = comment + "\nTest end time: " + endTime;

          if (log.allResults.executionLink) {
            comment = comment + "\nReport available here: " + log.allResults.executionLink;
          }
          if (this.config.additionalInfo && !(this.config.additionalInfo === "" )) {
            comment = comment + "\nAdditional info: " + this.config.additionalInfo;
          }

          await this.jira.postComment(issueKey, comment);
      } catch (error) {
          console.error('An error occured in JiraCommentPublisher.publish, error:' + error);
          return;
      }
    }
}
