import moment from 'moment'

function date2s (date) {
  return moment(date).format('DD.MM.')
}

function time2s (date) {
  return moment(date).format('HH:mm')
}

function datetime2s (date) {
  return moment(date).format('DD.MM. HH:mm')
}

function normalize (item, type) {
  return item ? String(item).replace(/\s+/g, ' ').trim() : null
}

function fileSize (int) {
  let value
  if (int > Math.pow(2, 10)) {
    value = `${int / Math.pow(2, 10)}kB`
  }
  if (int > Math.pow(2, 20)) {
    value = `${int / Math.pow(2, 20)}MB`
  }
  if (int > Math.pow(2, 30)) {
    value = `${int / Math.pow(2, 30)}GB`
  }
  return value
}

function normalizePhone (item) {
  let phone = String(item).replace(/\s|\+|\/|,|-|'/g, '').replace(/\(0\)/, '').replace(/^0+/, '')
  if (phone.match(/[^\d*]/)) {
    return `FEHLER (nicht-numerische Zeichen): ${phone}`
  }
  if (phone.length === 0) {
    return null
  } else if (phone.length === 9) {
    // Assume swiss number
    phone = `+41${phone}`
  } else if (phone.length === 11) {
    phone = `+${phone}`
  } else {
    return `FEHLER (falsche Länge): ${phone}`
  }

  return phone
}

function filterFuzzy (item, filter) {
  const lowerCaseItem = item.toLowerCase()
  const substrings = filter.toLowerCase().split(/\s+/)
  let lastIndex = 0
  const indices = substrings.map(substring => {
    const index = lowerCaseItem.subString(lastIndex).indexOf(substring)
    if (index === -1) {
      return null
    } else {
      const startIndex = lastIndex + index
      const endIndex = startIndex + substring.length
      lastIndex = endIndex
      return {startIndex, endIndex}
    }
  })
  return indices
}

function filterExact (item, filter) {
  return item === filter
}

export { date2s, time2s, datetime2s, normalize, normalizePhone, fileSize, filterFuzzy, filterExact }
