'use strict';

// LOCALS
const tools = require('../tools');
const apiUtils = require('../api-utils');
const configUtils = require('../../csdr/config/config-utils');

// ARGS
const { dryRun, debug, debugNotification, skipNotification } = tools.getArgs();


const getChannelHook = module.exports.getChannelHook = (channelName) => {
  const { msteamsHooksArray } = tools.getArgs();

  const msteamsHook = msteamsHooksArray.filter((h) => {
    return Object.keys(h)[0] === channelName;
  })[0];

  if (!msteamsHook) {
    tools.logInfo(`Channel hook can't be found for ${channelName} - check _CSDR_ARGS entries in gitlab pipeline configuration`);

    // TODO set default channels in global config by type
    // const globalConfig = configUtils.global.getConfigOptions();
    return;
  }

  return msteamsHook[channelName];
}


const createPayload = (messageContent) => {
  const emojis = {
    rocket: "&#x1f680;",
    warning: "&#x26A0;",
    sucess: "✅",
    failure: "❌",
  };

  const statuses = {
    success: { text: '[BUILD SUCCESS]', color: '26A65B', emoji: emojis.sucess},
    failure: { text: '[BUILD FAILED]', color: 'D91E18', emoji: emojis.failure}
  };


  // set color : success or failure
  let status = statuses.success;
  if (messageContent.buffer.filter(m => m.status === 'SUCCESS').length === 0) {
    status = statuses.failure;
  }

  // final status message on the stack
  const finalMessage = messageContent.buffer.slice(-1)[0];

  // set released version
  const version = finalMessage.version;

  // set commit history
  let commitHistory = [], exceptionDetails = [];
  if (status === statuses.success) {
    commitHistory = finalMessage.detailTextArray;
  } else {
    exceptionDetails = finalMessage.detailTextArray;
  }

  // set summary
  const itemName = messageContent.buffer[0].scope;
  let summary = `${status.emoji} :: ${status.text} - ${itemName}`;
  if (version) {
    summary +=  ` - ${version}`;
  }

  // set release sections
  const publications = messageContent.buffer.filter(m => m.text !== null && m.text.indexOf(':rocket:') > -1);
  const stylesReport = messageContent.buffer.filter(m => m.text !== null && m.text.indexOf('STYLES AUDIT REPORT') > -1)[0];
  const dependenciesReport = messageContent.buffer.filter(m => m.text !== null && m.text.indexOf('Dependencies audit') > -1)[0];
  const pipelineLink = messageContent.buffer.filter(m => m.text !== null && m.text.indexOf('//gitlab') > -1)[0];

  let sections = [];

  if (status === statuses.success) {
    sections.push({
      "startGroup": true,
      "activityTitle": `${emojis.sucess} PACKAGE BUILD SUCCESS !! ${emojis.sucess}`
    });

    publications.forEach((p) => {
      sections.push({
        "activityTitle": `package published : ${version}`,
        "facts": [],
        "activityText": p.text.replace(':rocket:', emojis.rocket).replace('- *VERSION*', '')
      });
    });

    if (dependenciesReport && dependenciesReport.text) {
      sections.push({
        "startGroup": true,
        "activityTitle": "Dependencies vulnerabilities audit",
        "activityText": dependenciesReport.text.replace('"Dependencies audit detected vulnerabilities :', ''),
      });
    }

    if (stylesReport && stylesReport.text) {
      let stylesReportCleanup;
      stylesReportCleanup = tools.replaceAll(stylesReport.text, ':no_entry:', `${emojis.failure} - INVALID : `);
      stylesReportCleanup = tools.replaceAll(stylesReportCleanup, ':large_green_circle:', `${emojis.sucess} - OK : `);
      stylesReportCleanup = tools.replaceAll(stylesReportCleanup, ':warning:',  `${emojis.warning} - WARNING : `);
      stylesReportCleanup = tools.replaceAll(stylesReportCleanup, '\n', '\n\n');

      sections.push({
        "startGroup": true,
        "activityTitle": "Styles report",
        "activityText": stylesReportCleanup
      });
    }

    if (commitHistory.length > 0) {
      sections.push({
        "activityTitle": "Commit history since last release tag",
        "activityText": commitHistory.slice(0, 25).join(' --- ').substr(0, 7500)
      });
    }



  } else {
    sections.push({
      "startGroup": true,
      "activityTitle": `${emojis.failure} PACKAGE BUILD ERROR !! ${emojis.failure}`,
    });

    if (exceptionDetails.length > 0) {
      if (finalMessage.detailText) {
        let exceptionCleanup;
        exceptionCleanup = tools.replaceAll(finalMessage.detailText.substr(0, 7500), '\r', '');
        exceptionCleanup = tools.replaceAll(exceptionCleanup, '\n', ' ---- ');
        exceptionCleanup = tools.replaceAll(exceptionCleanup, '~', '');
        exceptionCleanup = tools.replaceAll(exceptionCleanup, '--', '');

        sections.push({
          "activityTitle": `${finalMessage.detailTitle}`,
          "activityText": exceptionCleanup,
        });
      }
    }
  }

  sections.push({
    "startGroup": true,
    "facts": [
      {
        "name": "Duration : ",
        "value": `**${messageContent.durationMinSec}**`
      },
    ]
  });

  if (pipelineLink) {
    let textValue = tools.replaceAll(pipelineLink.text, ':arrow_forward: :arrow_forward: Pipeline ID :', '');
    sections.push({
      "startGroup": true,
      "facts": [
        {
          "name": "Pipeline ID : ",
          "value": `${textValue}`
        },
      ]
    });
  }


  // return payload
  return {
    "@type": "MessageCard",
    "@context": "https://schema.org/extensions",
    "summary": summary,
    "themeColor": status.color,
    "title": summary,
    "sections": sections
  };
}


module.exports.sendMessage = (config, messageContent, standalone = false) => {
  tools.logTitle('Sending MS teams message');

  const channelHook = getChannelHook(config.MSTEAMS_CHANNEL);

  if (!channelHook) {
    return Promise.resolve();
  }

  const payload = createPayload(messageContent);

  if (debug && debugNotification) {
    console.log(JSON.stringify(messageContent, null, 2));
    console.log(JSON.parse(JSON.stringify(payload, null, 2)));
  }

  return Promise.resolve()
    .then(() => {
      let host;

      if (standalone) {
        host = configUtils.global.getConfigOptionsStandalone().MSTEAMS_HOST;
      } else {
        host = configUtils.global.getConfigOptions().MSTEAMS_HOST;
      }

      if (dryRun || skipNotification) {
        tools.logInfo('DRY-RUN or skipNotification active...skipping');
        return Promise.resolve();
      } else {
        return apiUtils.post(host, channelHook, JSON.parse(JSON.stringify(payload, null, 2)));
      }

    })
    .then((response) => {
      console.log(response);
    })
    .catch(e => {
      throw e;
    })
}
