const DEFAULT_DURATION = 1000
const globalListeners = []

function getToastFromState(state = {}) {
  const errorText = String(state.errorText || '').trim()
  const systemTip = String(state.systemTip || '').trim()

  if (errorText) {
    return {
      text: errorText,
      type: 'error'
    }
  }

  if (systemTip) {
    return {
      text: systemTip,
      type: 'info'
    }
  }

  return {
    text: '',
    type: ''
  }
}

function createPageToast(page, initialState = {}, duration = DEFAULT_DURATION) {
  let active = true
  let timer = null
  let lastText = getToastFromState(initialState).text

  function clearTimer() {
    if (!timer) return

    clearTimeout(timer)
    timer = null
  }

  function clear() {
    clearTimer()
    page.setData({
      toastText: '',
      toastType: ''
    })
  }

  function show(text, type) {
    if (!active) return

    clearTimer()
    page.setData({
      toastText: text,
      toastType: type || 'info'
    })

    timer = setTimeout(() => {
      timer = null
      page.setData({
        toastText: '',
        toastType: ''
      })
    }, duration)
  }

  function showExternal(text, type) {
    const toastText = String(text || '').trim()

    if (!toastText) {
      lastText = ''
      return
    }

    if (!active) {
      lastText = toastText
      return
    }

    if (toastText === lastText) return

    lastText = toastText
    show(toastText, type)
  }

  function showFromState(state) {
    const toast = getToastFromState(state)

    if (!toast.text) {
      lastText = ''
      return
    }

    if (!active) {
      lastText = toast.text
      return
    }

    if (toast.text === lastText) return

    lastText = toast.text
    show(toast.text, toast.type)
  }

  function setActive(nextActive) {
    active = !!nextActive

    if (!active) clear()
  }

  function destroy() {
    clear()
    const index = globalListeners.indexOf(showExternal)
    if (index >= 0) globalListeners.splice(index, 1)
  }

  globalListeners.push(showExternal)

  return {
    clear,
    destroy,
    show,
    showFromState,
    setActive
  }
}

function notifyPageToast(text, type = 'info') {
  globalListeners.slice().forEach((listener) => {
    listener(text, type)
  })
}

module.exports = {
  createPageToast,
  notifyPageToast
}
