import { SET_LOCAL_FORM } from '@@/store/types'
import { CLEAR_LOADED_DATA } from '@/store/utils/types'

export default {
  namespaced: true,
  state: {},
  getters: {},
  actions: {
    setLocalForm({ commit, dispatch }, payload) {
      let { namespace, key } = payload
      let oldData = sessionStorage.getItem(key)
      if (oldData) {
        payload.formData = { ...JSON.parse(oldData), ...payload.formData }
      }
      dispatch(namespace + key, payload.formData, { root: true })
      commit(SET_LOCAL_FORM, payload)
    },
    clearData({ dispatch }, exclude = []) {
      return dispatch(
        'clearLoadedData',
        ['autoship', 'membership', 'enrollment', 'shippingAndPayment'].filter(f => !exclude.includes(f))
      )
    },
    clearLoadedData({ commit }, payload) {
      ;[
        '3rdPartyCheckoutEnrolment/',
        '3rdPartyCheckoutAutoship/',
        '3rdPartyCheckoutMembership/',
        '3rdPartyCheckoutShippingAndPayment/',
      ].forEach(function(namespace) {
        if (Array.isArray(payload)) {
          payload.forEach(type => {
            commit(namespace + CLEAR_LOADED_DATA, type, { root: true })
          })
        } else {
          commit(namespace + CLEAR_LOADED_DATA, payload, { root: true })
        }
      })
    },
  },
  mutations: {
    // eslint-disable-next-line no-empty-pattern
    [SET_LOCAL_FORM]({}, data = { key: '', formData: {} }) {
      let { key, formData } = data
      sessionStorage.setItem(key, JSON.stringify(formData))
    },
  },
}
