import startOfWeek from 'date-fns/startOfWeek'
import addDays from 'date-fns/addDays'

type Args = {
  date: Date,
  lang: string,
  monthType?: 'long' | 'short',
}

const getMonthName = ({
  date,
  lang,
  monthType,
}: Args) => (
  date.toLocaleString(lang, { month: monthType })
)

export const getDisplayDate = ({
  date,
  lang,
  monthType = 'long',
}: Args) => ({
  day: date.getDate(),
  month: getMonthName({
    date,
    lang,
    monthType,
  }),
  year: date.getFullYear(),
})

export const getWeekName = (date: Date, locale: string) => (
  new Intl.DateTimeFormat(locale || 'en', { weekday: 'short' }).format(date)
)

const createDayGetter = (weekStart: Date, locale: string) => (day: number) => {
  const dayDate = addDays(weekStart, day)
  return {
    date: dayDate,
    name: getWeekName(dayDate, locale),
  }
}

type Week = {
  date: Date,
  name: string,
}

export const getWeeks = (date: Date, locale: string) => {
  const weekStart = startOfWeek(date, { weekStartsOn: 1 })
  const getWeekDay = createDayGetter(weekStart, locale)
  const week: Array<Week> = [
    getWeekDay(0),
    getWeekDay(1),
    getWeekDay(2),
    getWeekDay(3),
    getWeekDay(4),
    getWeekDay(5),
    getWeekDay(6),
  ]
  return week
}
