import { TransformerFunction } from './TransformerFunction';

export type Timestamp = `${string}:${string}:${string}.${string}`;
export const TIMESTAMP_DEFAULT = '00:00:00.000';

/**
 * Renders numeric seconds value as a timestamp
 * @param timeInSeconds seconds as a numeric value, can contain a fractional part
 * @returns timestamp string
 * @returns defaults to '00:00:00.000' if value is undefined or null
 */
export const formatSecondsToTimestamp: TransformerFunction<
  number,
  Timestamp
> = (timeInSeconds?: number | null): Timestamp => {
  if (
    timeInSeconds === null ||
    timeInSeconds === undefined ||
    typeof timeInSeconds !== 'number'
  ) {
    return TIMESTAMP_DEFAULT;
  }

  const pad = (num: number, size: number): string =>
    ('000' + num).slice(size * -1);
  const time = timeInSeconds.toFixed(3);
  const hours = Math.floor(Number(time) / 60 / 60);
  const minutes = Math.floor(Number(time) / 60) % 60;
  const seconds = Math.floor(Number(time) - minutes * 60);
  const milliseconds = time.slice(-3);

  return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}.${pad(
    Number(milliseconds),
    3,
  )}`;
};

/**
 * Takes a timestamp and turns it into seconds
 * @param timestamp string in the format of a timestamp
 * @returns seconds
 */
export const timestampToSeconds: TransformerFunction<Timestamp, number> = (
  timestamp: Timestamp,
): number => {
  const [hh, mm, ss] = timestamp.split(':');

  const totalSeconds = Number(hh) * 3600 + Number(mm) * 60 + Number(ss);

  return totalSeconds;
};
