import { forEach, last, multiply, range, map, prop, reduce } from 'rambda';
import { max, min } from 'ramda';

export const minTime = data => {
  const processorsMinTime = map(
    processorData => reduce(
      min,
      Infinity,
      map(prop('startTime'), processorData)
    ),
    data
  );

  return reduce(min, Infinity, processorsMinTime);
};

export const maxTime = data => {
  const processorsMaxTime = map(
    processorData => reduce(
      max,
      -Infinity,
      map(prop('startTime'), processorData)
    ),
    data
  );

  return reduce(max, -Infinity, processorsMaxTime);
};

export const normalizeData = data =>
  map(processorData => {
    // if startTime would be days (thousands of seconds), set step to day
    const step = 1; // >= 1

    const _minTime = Math.floor(minTime(data) / step);
    const _maxTime = Math.floor(maxTime(data) / step);

    const rangeTime = map(
      multiply(step),
      range(_minTime, _maxTime + 1)
    );

    const dataObj = reduce(
      (obj, row) => ({ ...obj, [row.startTime]: row }),
      {},
      processorData
    );

    forEach(startTime => {
      if (!dataObj[startTime]) {
        dataObj[startTime] = { startTime };
      }
    }, rangeTime);

    const filledData = Object.values(dataObj);

    filledData.push({ startTime: last(processorData).endTime });

    return filledData;
  }, data);