/**
 * Created by vivek on 21/2/17.
 */

import _ from 'lodash';

export function formatUnderscoreToSpaces(str) {
  return str.split('_').join(' ');
}

export function capitalizeString(str = '') {
  const newStr = [];
  const words = str.toLowerCase().split(' ');
  _.forEach(words, (value) => {
    const letters = value.split('');
    let tmpString = '';
    letters[0] = letters[0] && letters[0].toUpperCase();
    tmpString = letters.join('');
    newStr.push(tmpString);
  });
  return newStr.join(' ');
}

export function formatDotToColon(str) {
  return str.split('.').join(': ');
}

export function formatString(str) {
  let formattedString = formatDotToColon(str);
  formattedString = formatUnderscoreToSpaces(formattedString);
  formattedString = capitalizeString(formattedString);
  return formattedString;
}

export function formatCurrency(d, settings) {
  //  let decimal = 2;//(d % 1) != 0 ? 2 : 0;
  const { decimals } = settings;
  const numberSettings = [
    { value: 1E9, symbol: 'B' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' },
  ];
  for (let i = 0; i < numberSettings.length; i += 1) {
    if (d >= numberSettings[i].value) {
      return (d / numberSettings[i].value).toFixed(decimals) + numberSettings[i].symbol;
    }
  }
  return d.toFixed(decimals);
}

export function convertValueToDecimalUnit(value, formatSettings) {
  let formattedValue = value;
  if (!_.isEmpty(formatSettings)) {
    const decimals = formatSettings.decimals || 0;
    formattedValue = formattedValue.toFixed(decimals);
  }
  return formattedValue;
}

export function fillArrayWithZeros(data) {
  // not using Object.assgin() because it does not support deep cloning
  const zeroedData = JSON.parse(JSON.stringify(data));
  if (zeroedData.length > 1) {
    for (let j = 0; j < zeroedData.length; j + 1) {
      const zeroedFactKeys = Object.keys(zeroedData[j].factvalues);
      for (let i = 0; i < zeroedFactKeys.length; i + 1) {
        _.fill(zeroedData[j].factvalues[zeroedFactKeys[i]], 0);
      }
    }
  } else {
    const zeroedFactKeys = Object.keys(zeroedData);
    for (let i = 0; i < zeroedFactKeys.length; i + 1) {
      _.fill(zeroedData[zeroedFactKeys[i]], 0);
    }
  }
  return zeroedData;
}
