const MS = 1000;
const SS = 1;
const MM = 60 * SS;
const HH = 60 * MM;

const allowedTimeParts = ['hhh', 'hh', 'h', 'mm', 'm', 'ss', 's', 'SSS', 'SS', 'S'];
const allowedTimePatterns = new RegExp(`\\b(${allowedTimeParts.join('|')})\\b`, 'g');

const timeMap = (time: number) => {
  const hour = Math.floor(time / MS / HH).toString();
  const minute = Math.floor((time / MS / MM) % MM).toString();
  const second = Math.floor((time / MS) % MM).toString();
  const milliSecond = time % MS;

  return {
    hhh: hour.padStart(3, '0'),
    hh: hour.padStart(2, '0'),
    h: hour,
    mm: minute.padStart(2, '0'),
    m: minute,
    ss: second.padStart(2, '0'),
    s: second,
    SSS: Math.floor(milliSecond).toString().padStart(3, '0'),
    SS: Math.floor(milliSecond / 10)
      .toString()
      .padStart(2, '0'),
    S: Math.floor(milliSecond / 100)
      .toString()
      .padStart(1, '0'),
  };
};

/**
 * @param time number, example 1234567890
 * @param pattern string, example 'hhh:mm:ss:SSS'
 * @returns string, example '342:56:07:890'
 */
export const getFormattedTime = (time: number, pattern: string) => {
  const timeMapValue = timeMap(time);
  return pattern.replace(allowedTimePatterns, (part: string) => timeMapValue[part as keyof typeof timeMapValue]);
};

export const getDuration = (time = 0, withMS = false) => {
  const { h, mm, m, ss, s, SSS } = timeMap(time);

  const res = [];

  if (h === '0') {
    if (m === '0') {
      if (withMS) {
        res.push(s);
      } else {
        res.push('0', ss);
      }
    } else {
      res.push(m, ss);
    }
  } else {
    res.push(h, mm, ss);
  }

  if (withMS) {
    res.push(SSS);
  }

  return res.join(':');
};

export default {};
