
import { date as qdate, format } from 'quasar'
const { pad } = format

export default async ({ app, Vue }) => {
  let i18n = app.i18n

  function currency (val) {
    return typeof val === 'number' ? val.toFixed(2) + '€' : val
  }

  function date (val, format) {
    if (val == null) return val
    if (!(val instanceof Date)) {
      val = new Date(val)
    }
    return qdate.formatDate(val, format, app.i18n.t('date'))
  }

  function relDate (val) {
    if (val == null) return val
    if (!(val instanceof Date)) {
      val = new Date(val)
    }

    let dif = qdate.getDateDiff(new Date(), val, 'days')
    let day

    switch (dif) {
      case 0:
        day = 'today'
        break
      case 1:
        day = 'yesterday'
        break
      case -1:
        day = 'tomorrow'
        break
    }

    if (day) {
      day = i18n.t(day)
    } else {
      if (dif > 0 && dif <= 7) {
        day = qdate.formatDate(val, 'ddd', i18n.t('date'))
      } else {
        day = qdate.formatDate(val, 'ddd, MMMM Do', i18n.t('date'))
      }
    }

    return day
  }

  function relTime (val) {
    if (val == null) return val
    if (!(val instanceof Date)) {
      val = new Date(val)
    }
    return relDate(val) + ' ' + qdate.formatDate(val, 'H:mm:ss')
  }

  function elapsedTime (val) {
    if (val == null) return val
    if (!(val instanceof Date)) {
      val = new Date(val)
    }
    let now = (new Date()).getTime()
    val = Math.floor((now - val.getTime()) / 1000)

    let hours = Math.floor(val / 3600)
    val -= hours * 3600
    let minutes = Math.floor(val / 60)
    val -= minutes * 60
    let seconds = val

    return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}`
  }

  Vue.filter('currency', currency)
  Vue.filter('date', date)
  Vue.filter('relDate', relDate)
  Vue.filter('relTime', relTime)
  Vue.filter('elapsedTime', elapsedTime)
}
