export const formatNumeral = (n?: number) => {
  if (typeof n !== 'number') {
    return '';
  }

  if (!Number.isFinite(n)) {
    return '';
  }

  return new Intl.NumberFormat().format(n);
}

export const formatFileSize = (size?: number) => {
  if (typeof size !== 'number') {
    return '';
  }

  if (!Number.isFinite(size)) {
    return '';
  }

  if (size < (2 ** 10)) {
    return `${formatNumeral(size)} byte(s)`;
  }

  if (size < (2 ** 20)) {
    return `${(size / (2 ** 10)).toFixed(3)} kiB`;
  }

  if (size < (2 ** 30)) {
    return `${(size / (2 ** 20)).toFixed(3)} MiB`;
  }

  if (size < (2 ** 40)) {
    return `${(size / (2 ** 30)).toFixed(3)} GiB`;
  }
};

export const formatSecondsDurationPrecise = (seconds: number) => {
  const secondsInt = Math.floor(seconds);
  const secondsFrac = seconds - secondsInt;
  const hh = Math.floor(secondsInt / 3600).toString().padStart(2, '0');
  const mm = Math.floor(secondsInt / 60 % 60).toString().padStart(2, '0');
  const ss = (secondsInt % 60).toString().padStart(2, '0');
  const sss = Math.floor(secondsFrac * 1000).toString().padStart(3, '0');
  return `${hh}:${mm}:${ss}.${sss}`;
};

export const formatSecondsDurationConcise = (seconds: number) => {
  const secondsInt = Math.floor(seconds);
  const mm = Math.floor(secondsInt / 60).toString().padStart(2, '0');
  const ss = (secondsInt % 60).toString().padStart(2, '0');
  return `${mm}:${ss}`;
};
