import PublisherUtils from './publisher-utils.js';
import * as utils from '../../utils.js';
import S3Service from '../../services/s3-service.js';
import path from 'path'
import fs from 'fs'

export default class S3Publisher {

  constructor( config ) {
    this.path = path;
    
    this.config = config;
    if (this.config.prefixRootKeyWithTime) {
      this.config.s3rootKey = PublisherUtils.getDateAndTimeForFile() + this.config.s3rootKey;
    }

    this.config.s3rootKey = this.config.s3rootKey + "_" + utils.getRandomdString(100);
    this.s3 = new S3Service();
    this.fs = fs;
  }

  async publish(reportFilePath) {
    let logStr = this.fs.readFileSync(reportFilePath, 'utf8');
    let log = JSON.parse(logStr);
    if (!logStr){
        throw new Error('Could not read logfile');
    }
    try {
      await this.s3.uploadDirectory({
        path: this.config.dirPath,
        params: {
          Bucket: this.config.s3Bucket
        },
        options: {},
        rootKey: this.config.s3rootKey
      })
    } catch (error) {
        console.error('An error occured in S3Publisher.publish, error:' + error);
        return;
    }
    let executionLink = "http://" + this.config.s3Bucket  + "." +  this.config.s3Server + "/" +  this.config.s3rootKey + "/" + this.config.indexFile;

    log.allResults['executionLink'] = executionLink
    if (log.groupedResults){
      let groups = Object.keys(log.groupedResults);
      groups.forEach(group => {
        log.groupedResults[group]['executionLink'] = executionLink;
      });
    }

    let filename = this.path.parse(reportFilePath).base;
    let jsonLink =  "http://" + this.config.s3Bucket  + "." +  this.config.s3Server + "/" +  this.config.s3rootKey + "/" + filename;
    log['jsonLink'] = jsonLink

    this.fs.writeFileSync(reportFilePath,
      JSON.stringify(log,null,2), function(err) {
            if (err) {
                return console.error("Error writing updated logfile in S3Publisher: " + err);
            }
        }
    );
    try {
      let key =  this.config.s3rootKey + '/' + filename;
      await this.s3.uploadFile({
        path: reportFilePath,
        params: {
          Bucket: this.config.s3Bucket,
          Key: key
        },
        options: {},
        rootKey: this.config.s3rootKey
      })
    } catch (error) {
        console.error('An error occured in S3Publisher.publish, error:' + error);
        return;
    }
  }
}
