'use strict';

// GLOBAL
const moment = require('moment');

// LOCAL
const tools = require('../tools');

// INNER MODS
const innerConfig = require('./config');
const innerTeamsUtils = require('./teams-utils');


// ---------------------------------------------------------------------------------------
// MESSAGE BUFFER
// - used for storing all message happening during a run
// - used for aggregating messages on a pipeline run to a single mail / ms teams push
// ---------------------------------------------------------------------------------------

const messageContent = {
  buffer: [],
  startTimestamp: null,
  endTimestamp: null,
  duration: null,
  durationSeconds: null,
  durationMinSec: null
};

module.exports.startStack = () => {
  messageContent.startTimestamp = moment();
}

module.exports.endStack = () => {
  messageContent.endTimestamp = moment();
  messageContent.duration = messageContent.endTimestamp - messageContent.startTimestamp;
  const start = messageContent.startTimestamp, end = messageContent.endTimestamp;
  messageContent.durationSeconds = end.diff(start, 's');
  const getMinSec = (s) => { return(s-(s%=60))/60+'m'+(9<s?':':':0')+s+'s'; }
  messageContent.durationMinSec = getMinSec(messageContent.durationSeconds);
}

module.exports.pushMessage = (message) => {
  messageContent.buffer.push(message);
}


const sendMessage = (config, standalone = false) => {
  if (config.CLIENT === 'SLACK') {
    return Promise.resolve();
  }

  return Promise.resolve()
    .then(() => {
      if (config.CLIENT === 'MSTEAMS') {
        return innerTeamsUtils.sendMessage(config, messageContent, standalone);
      }
    })
    .catch((e) => {
      throw e;
    })
}


module.exports.sendPackageMessage = (pkg) => {
  tools.logTitle(`Sending package message for ${pkg.name}`);

  const config = innerConfig.getPackageConfig(pkg);

  tools.logInfo('Notification config : ');
  console.log(config);

  return Promise.resolve()
    .then(() => {
      return sendMessage(config, pkg.standalone);
    })
    .catch((e) => {
      throw e;
    })
}


module.exports.sendProjectMessage = (project) => {
  tools.logTitle(`Sending project message for ${project.name}`);

  const config = innerConfig.getProjectConfig(project);

  tools.logInfo('Notification config : ');
  console.log(config);

  return Promise.resolve()
    .then(() => {
      return sendMessage(config);
    })
    .catch((e) => {
      throw e;
    })
}
