/**
 * Converting date object to the UTC time string
 */
export const dateToUtcTime = (date: Date) => {
  let timeStr = ('0' + date.getUTCHours()).slice(-2) + ':'
  timeStr = timeStr + ('0' + date.getUTCMinutes()).slice(-2) + ':'
  timeStr = timeStr + ('0' + date.getUTCSeconds()).slice(-2)
  return timeStr
}

/**
 * Converts date object to the time string
 */
export const dateToTime = (date: Date) => {
  let timeStr = ('0' + date.getHours()).slice(-2) + ':'
  timeStr = timeStr + ('0' + date.getMinutes()).slice(-2) + ':'
  timeStr = timeStr + ('0' + date.getSeconds()).slice(-2)
  return timeStr
}

/**
 * Normalises a 24-hour time STRING to zero-padded `HH:mm:ss`.
 *
 * The `intl-time` cell type (validator + native `<input type=time>` editor) is
 * strict and rejects `H:mm[:ss]`, so such a value paints red and the editor
 * opens empty. Pad the hour and default the seconds so the value validates.
 *
 * Non time-like input is returned unchanged.
 */
export const padTimeString = (value: string): string => {
  const match = value.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/)
  if (!match) return value
  const [, hours, minutes, seconds] = match
  return `${hours.padStart(2, '0')}:${minutes}:${seconds ?? '00'}`
}

/**
 * Converts date object to the YYYY-MM-DD
 */
export const dateFormat = (date: Date) => {
  return (
    date.getFullYear() +
    '-' +
    ('0' + (date.getMonth() + 1)).slice(-2) +
    '-' +
    ('0' + date.getDate()).slice(-2)
  )
}
