const month = [
  'янв',
  'фев',
  'мар',
  'апр',
  'май',
  'июн',
  'июл',
  'авг',
  'сен',
  'окт',
  'ноя',
  'дек',
]

class DateHelper {
  format(timestamp: number): string {
    if (!timestamp) {
      return ''
    }

    const currentDate = new Date()
    const targetDate = this.getDateFromTimestamp(timestamp)

    const diffDays = differenceInDays(currentDate, targetDate)
    const isCurrentYear = differenceInYears(currentDate, targetDate) === 0

    if (diffDays === 0) {
      return getTimeAsString(targetDate)
    }

    if (diffDays > 0 && isCurrentYear) {
      return `${getMonthAsString(targetDate)}, ${getTimeAsString(targetDate)}`
    }

    return `${getMonthAsString(targetDate)}, ${getYearAsString(targetDate)}`
  }

  getFullDate(timestamp: number): string {
    if (!timestamp) {
      return ''
    }

    const targetDate = this.getDateFromTimestamp(timestamp)

    return `${getMonthAsString(targetDate)}, ${getYearAsString(targetDate)}`
  }

  getHumanizeTime(timestamp: number) {
    return getTimeAsString(this.getDateFromTimestamp(timestamp))
  }

  getDateFromTimestamp(timestamp: number): Date {
    const targetDate = new Date()

    targetDate.setTime(
      timestamp.toString().length < 13 ? timestamp * 1000 : timestamp
    )

    return targetDate
  }
}

export function getTimeAsString(date: Date): string {
  return `${addZero(date.getHours())}:${addZero(date.getMinutes())}`
}

export function getMonthAsString(date: Date): string {
  return `${addZero(date.getDate())} ${month[date.getMonth()]}`
}

export function getYearAsString(date: Date): string {
  return date.getFullYear().toString()
}

export function differenceInDays(date1: Date, date2: Date) {
  const diffTime = Math.abs(+date2 - +date1)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

function differenceInYears(date1: Date, date2: Date) {
  return Math.abs(date1.getFullYear() - date2.getFullYear())
}

function addZero(value: number): string {
  return `${value < 10 ? '0' : ''}${value}`
}

export default new DateHelper()
