import { get, post } from '@/store/utils/api'
import { NOTIFICATION_GET_NOTIFICATION_LIST, NOTIFICATION_READ_NOTIFICATION_LIST } from '@/store/utils/apiUrls'
import * as T from '@/store/utils/types'
import querystring from 'querystring'

export const loadUserNotifications = async ({ commit, dispatch }, payload = {}) => {
  await dispatch('removeError', 'loadNotification')
  commit(T.PROCESSING_STARTED, 'loadingNotification')
  let cancelToken = await dispatch('generateCancelToken', 'notification')

  let query = '?' + querystring.stringify(payload)
  return await get(NOTIFICATION_GET_NOTIFICATION_LIST + query, cancelToken.token)
    .then(response => {
      commit(T.SET_NOTIFICATION_LIST, response.data)
      return response.data.data
    })
    .catch(error => {
      if (error.__CANCEL__ === undefined) {
        commit(T.SET_NOTIFICATION_LIST, {})
        dispatch('logError', { loadNotification: error })
      }
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingNotification')
    })
}

export const readUserNotification = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'readNotification')
  post(NOTIFICATION_READ_NOTIFICATION_LIST, payload)
    .catch(error => {
      dispatch('logError', { read_notification: error })
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'readNotification')
    })
}
