const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const getToken = () => {
  const map = ['E','q','u','i','n','W','A','b','C','d']
  const errKey = ['f','g','h','j','k','l']
  let time = new Date();
  const m = '' + (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1)
  const d = '' + (time.getDate() < 10 ? '0' + time.getDate() : time.getDate())
  const h = '' + (time.getHours() < 10 ? '0' + time.getHours() : time.getHours())
  let min = '' + (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes())
  const seconds = '' + (time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds())
  min = '20';
  let ident = Math.round(Math.random() * 7)
  let beforeStr = map[m[0]] + errKey[Math.round(Math.random() * 5)]
      + map[m[1]] + errKey[Math.round(Math.random() * 5)]
      + map[d[0]] + errKey[Math.round(Math.random() * 5)]
      + map[d[1]] + errKey[Math.round(Math.random() * 5)]
      + map[h[0]] + errKey[Math.round(Math.random() * 5)]
      + map[h[1]] + errKey[Math.round(Math.random() * 5)]
      + map[min[0]] + errKey[Math.round(Math.random() * 5)]
      + map[min[1]] + errKey[Math.round(Math.random() * 5)]
      + map[seconds[0]] + errKey[Math.round(Math.random() * 5)]
      + map[seconds[1]] + errKey[Math.round(Math.random() * 5)]
  let finalStr = beforeStr.substring(0,ident) + ident + map[ident] + beforeStr.substring(ident)
  return finalStr
}

module.exports = {
  formatTime,
  formatDate,
  getToken
}
