export function leftpad(value: number | string = 0, size: number) {
  let s = value + '';
  while (s.length < size) s = '0' + s;
  return s;
}

export function rightpad(value: number | string = 0, size: number) {
  let s = value + '';
  while (s.length < size) s = s + '0';
  return s;
}

export function formatPercent(value: number | string) {
  if (typeof value === 'undefined' || value === null) return '';
  const [left, right] = value.toString().split('.');
  return `${leftpad(left || 0, 2)}.${rightpad(right || 0, 2)}`;
}

export const formatTime = (value: number | string) => {
  return !!value ? new Date(value).toLocaleTimeString() : '';
};

export const formatDate = (value: number | string) => {
  return !!value ? new Date(value).toLocaleDateString() : '';
};

export const formatDateTime = (value: number | string) => {
  return !!value ? `${formatDate(value)} ${formatTime(value)}` : '';
};

export function formatCurrency(value: number | string, currency: string, decimals: number = 2) {
  const locale = navigator.language || navigator.languages[0];
  const formatter = new Intl.NumberFormat(locale, {
    style: 'currency',
    currency,
  });
  let valueToFormat = (+value).toFixed(decimals);
  return formatter.format(+valueToFormat || 0);
}

export function formatNumber(value: number | string) {
  const locale = navigator.language || navigator.languages[0];
  const formatter = new Intl.NumberFormat(locale);
  return formatter.format(+value || 0);
}

export const formatPercentage = (value: string | number) => (value ? `${(+value).toFixed(2)}%` : '00.00%');

export const formatDiff = (value: string | number, isPercent = false, decimals = false) =>
  value ? `${+value > 0 ? '+' : ''}${(+value).toFixed(decimals ? 2 : 0)}${isPercent ? '%' : ''}` : '';

export function daysAgo(first: number, last: number) {
  return Math.ceil(Math.abs(first - last) / (1000 * 60 * 60 * 24));
}

export function formatByThousands(value: number) {
  const locale = navigator.language || navigator.languages[0];
  const formatter = new Intl.NumberFormat(locale, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
  if (value >= 1000000) {
    return `${formatter.format(value / 1000000)}M`;
  }
  if (value >= 1000) {
    return `${formatter.format(value / 1000)}K`;
  }
  return formatter.format(value);
}
