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

export default class ObjectStorePublisher {

  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.os = new ObjectStoreService(this.config.s3ClientConfig);
    this.fs = fs;
    if (config.acl) {
      this.acl = config.acl;
    }
  }

  async publish(reportFilePath = null) {
    console.log("Running ObjectStorePublisher");
    let log = {};

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

    try {
      let params = {
        Bucket: this.config.s3Bucket
      }
      if (this.acl) {
        params.ACL = this.acl;
      }
      await this.os.uploadDirectory(this.config.dirPath, params, this.config.s3rootKey);
    } catch (error) {
      console.error('An error occured in ObjectStorePublisher.publish, error:' + error);
      return;
    }

    let executionLink = this.config.s3ClientConfig.endpoint + "/" + this.config.s3Bucket + "/" + this.config.s3rootKey + "/" + this.config.indexFile;
    console.log(`Report available at: ${executionLink}`);

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

    if (reportFilePath) {
      let filename = this.path.parse(reportFilePath).base;
      log['s3rootKey'] = this.config.s3rootKey

      this.fs.writeFileSync(reportFilePath,
        JSON.stringify(log, null, 2), function (err) {
          if (err) {
            return console.error("Error writing updated logfile in ObjectStorePublisher: " + err);
          }
        }
      );
      try {
        let key = this.config.s3rootKey + '/' + filename;
        let params = {
          Bucket: this.config.s3Bucket,
          Key: key
        }
        if (this.acl) {
          params.ACL = this.acl;
        }
        let reportFileStats = fs.statSync(reportFilePath);
        console.log("Reportfile SIZE is: " + reportFileStats.size / (1024 * 1024) + " MB");
        if (reportFileStats.size < (125 * (1024 * 1024))) {
          // Only upload if the size is less then 125 MB
          await this.os.uploadFile(reportFilePath, params, this.config.s3rootKey)
        }
      } catch (error) {
        console.error('An error occured in ObjectStorePublisher.publish, error:' + error);
        return;
      }
    }
  }
}
