import { format } from 'date-fns'
import type { Locale } from 'date-fns'
import { enUS, fr } from 'date-fns/locale'
import ArrayUtils from '~/services/utils/arrayUtils'

export const enum supportedLocales {
  FR = 'fr',
  EN = 'en',
}

const defaultLocale = 'fr'

export default class DateUtils {
  public static format(date: Date, fmt: string): string {
    return format(date, fmt)
  }

  /**
   * Formate la ou les dates au format donné et retourne la liste concaténée
   *
   * @param dates
   * @param fmt
   * @param sep
   */
  public static formatAndConcat(
    dates: Date | Array<Date>,
    fmt: string,
    sep: string = ' - '
  ): string {
    dates = Array.isArray(dates) ? dates : [dates]
    return dates.map((d) => this.format(d, fmt)).join(sep)
  }

  /**
   * Trie les dates par ordre chronologique
   *
   * @param dates
   * @param reverse
   */
  public static sort(
    dates: Array<Date>,
    reverse: boolean = false
  ): Array<Date> {
    return ArrayUtils.sort(dates, reverse) as Array<Date>
  }

  public static getFnsLocale(code: supportedLocales): Locale {
    const mapping = {
      en: enUS,
      fr,
    }
    return mapping[code] ?? mapping[defaultLocale]
  }

  public static getShortFormatPattern(code: supportedLocales): string {
    const mapping = {
      en: 'MM/dd/yyyy',
      fr: 'dd/MM/yyyy',
    }
    return mapping[code] ?? mapping[defaultLocale]
  }

  public static getFormatPattern(code: supportedLocales): string {
    const mapping = {
      en: 'MM/dd/yyyy HH:mm',
      fr: 'dd/MM/yyyy HH:mm',
    }
    return mapping[code] ?? mapping[defaultLocale]
  }

  public static formatIsoShortDate(date: Date): string {
    return format(date, 'yyyy-MM-dd')
  }
}
