const durationToHumanReadable = require("./durationToHumanReadable");
const moment = require("moment");
const getLifecycleStatusColor = require("./getLifecycleStatusColor");
const _ = require("lodash");

const calculateStatusDuration = (transitions, statuses) => {
  let statusDuration = {};
  let totalDuration = 0;
  let totalCurrentStatusDuration = null;
  let summations = [];

  transitions.forEach((transition) => {
    let duration = transition.duration;
    totalDuration += duration;
    if (transition.start && !transition.end) {
      const startMoment = moment(transition.start);
      const nowMoment = moment();
      const duration = moment.duration(nowMoment.diff(startMoment));
      totalCurrentStatusDuration = {
        value: duration.asMilliseconds(),
        humanReadable: durationToHumanReadable(duration)
      };
    }

    if (!transition.prev_value) {
      statusDuration[transition.value] = {
        value: duration,
        humanReadable: durationToHumanReadable(moment.duration(duration))
      };
    } else {
      if (statusDuration[transition.value]) {
        statusDuration[transition.value].value += duration;
        statusDuration[transition.value].humanReadable = durationToHumanReadable(
          moment.duration(statusDuration[transition.value].value)
        );
      } else {
        statusDuration[transition.value] = {
          value: duration,
          humanReadable: durationToHumanReadable(moment.duration(duration))
        };
      }
    }
  });

  // Calculate the percentage for each status
  // Calculate the percentage for each status
  let totalPercentage = 0;
  const statusKeys = Object.keys(statusDuration);
  statusKeys.forEach((status, index) => {
    if (index !== statusKeys.length - 1) {
      const percentage = (statusDuration[status].value / totalDuration) * 100;
      totalPercentage += percentage;
      statusDuration[status].percentage = percentage;
    } else {
      statusDuration[status].percentage = 100 - totalPercentage;
    }
  });

  for (let [status, { value, humanReadable }] of Object.entries(statusDuration)) {
    if (status !== "total") {
      summations.push({
        status,
        value,
        humanReadable,
        percentage: statusDuration[status].percentage,
        color: getLifecycleStatusColor(status),
        roundedPercentage: `${Math.round(statusDuration[status].percentage)}%`
      });
    }
  }

  const humanReadableTotal = durationToHumanReadable(moment.duration(totalDuration));

  return {
    summations:
      _.isArray(statuses) && !_.isEmpty(statuses)
        ? summations.sort((a, b) => {
            return statuses.indexOf(a.status) - statuses.indexOf(b.status);
          })
        : summations,
    totalStatuses: summations.length,
    total: totalDuration,
    totalCurrentStatusDuration,
    humanReadableTotal
  };
};
module.exports = calculateStatusDuration;
