import * as T from '../../utils/types'
import helpers from '@/helpers'
import _ from 'lodash'

export const logError = ({ commit }, payload) => {
  for (let key in payload) {
    let errorLog = {}
    if (helpers.isSet(payload[key], 'response.data.error')) {
      // is an http response error
      errorLog = { name: key, message: payload[key].response.data.error }
    } else {
      // normal error
      errorLog = { name: key, message: payload[key] }
    }
    commit(T.ADD_ERROR, errorLog)
    if (process.env.NODE_ENV !== 'production') {
      if (helpers.isSet(errorLog, 'message.stack')) {
        // eslint-disable-next-line
        console.error(helpers.getValue(errorLog, 'message.stack'))
      } else if (helpers.isSet(errorLog, 'stack')) {
        // eslint-disable-next-line
        console.error(helpers.getValue(errorLog, 'stack'))
      }
    }
  }
}

export const showNotice = ({ commit }) => {
  commit(T.NOTICE_SHOW, true)
}

export const hideNotice = ({ commit }) => {
  commit(T.NOTICE_SHOW, false)
}

export const noticeReadByMatch = ({ commit, getters }, properties = {}) => {
  let notices = _.filter(getters.getUnreadNotices, properties)
  notices.forEach(notice => {
    commit(T.NOTICE_READ, notice.id)
  })
}

export const noticeReadByTags = ({ commit, getters }, tags = []) => {
  let notices = _.filter(getters.getUnreadNotices, notice => _.intersection(notice.tags || [], tags).length > 0)
  notices.forEach(notice => {
    commit(T.NOTICE_READ, notice.id)
  })
}

export const noticeAdd = ({ commit }, notice) => {
  commit(T.NOTICE_ADD, notice)
}

export const noticeRead = ({ commit }, id) => {
  commit(T.NOTICE_READ, id)
}

export const removeError = ({ commit }, name) => {
  commit(T.REMOVE_ERROR, name)
}

export const resetError = ({ commit }, name) => {
  commit(T.RESET_ERROR, name)
}

export const resetAllErrors = ({ commit }, name) => {
  commit(T.RESET_ERROR_ALL, name)
}

export const showiSPPopup = ({ commit }) => {
  commit(T.ISP_POPUP_SHOW, true)
}

export const hideiSPPopup = ({ commit }) => {
  commit(T.ISP_POPUP_SHOW, false)
}

export const seenAnnouncement = ({ commit }) => {
  commit(T.IS_ANNOUNCEMENT_SEEN, true)
}
