/* globals i18n */
import { helper } from 'ember-helper';

const base = 1024;
const sizes = [
  [Math.pow(base, 1), 'KB'],
  [Math.pow(base, 2), 'MB'],
  [Math.pow(base, 3), 'GB']
];
const DEFAULT_SEPARATOR = i18n('of');

export default helper(([partial, total], { separator = DEFAULT_SEPARATOR }) => {
  if (partial === undefined || total === undefined) {
    return '';
  }

  let unitValue, label;
  for (let i = 0; i < sizes.length; i++) {
    [unitValue, label] = sizes[i];

    if (total / unitValue < 999.5) {
      break;
    }
  }

  let partialValue = truncate(partial / unitValue);
  let totalValue = truncate(total / unitValue);
  return `${partialValue} ${separator} ${totalValue}${label}`;
});

// Only show decimals when needed to show 3 significant digits
function truncate(num) {
  let result;
  if (100 <= num) {
    result = num.toFixed();
  } else if (10 <= num && num < 100) {
    result = num.toFixed(1);
  } else {
    result = num.toFixed(2);
  }

  return result;
}
