import { APP_MEMBERSHIP_FORM, EKBD_SPONSOR } from '@@/store/localStorageKeys'
import { SET_MEMBERSHIP_FORM } from '@@/store/types'
import _ from 'lodash'
import Vue from 'vue'
import * as T from '@/store/utils/types'

let defaultMembershipForm = {
  country: {},
  country_id: null,
  language_id: null,
  enrolment_type_id: null,
  sponsor: {
    sponsor_user_id: null,
    sponsor_name: '',
    sponsor_member_id: '',
  },
  status: false,
}

export default {
  namespaced: true,
  state: {
    [APP_MEMBERSHIP_FORM]: JSON.parse(sessionStorage.getItem(APP_MEMBERSHIP_FORM)) || defaultMembershipForm,
    sponsorIBOFromShareLink: sessionStorage.getItem(EKBD_SPONSOR) || false,
  },
  getters: {
    getMembershipInfo: state => {
      return state[APP_MEMBERSHIP_FORM]
    },
    getMembershipInfoIsValid: state => {
      return Vue.prototype.$helpers.getValue(state[APP_MEMBERSHIP_FORM], 'status')
    },
    getSponsorIBOFromLink: state => {
      return state.sponsorIBOFromShareLink
    },
  },
  actions: {
    [APP_MEMBERSHIP_FORM]({ commit }, payload) {
      commit(SET_MEMBERSHIP_FORM, payload)
    },
    removeEkbdSponsor() {
      sessionStorage.removeItem(EKBD_SPONSOR)
    },
  },
  mutations: {
    [SET_MEMBERSHIP_FORM](state, data) {
      state[APP_MEMBERSHIP_FORM] = _.cloneDeep(data)
    },
    [T.CLEAR_LOADED_DATA](state, type) {
      if (type === 'membership' || !type) {
        state[APP_MEMBERSHIP_FORM] = defaultMembershipForm
        sessionStorage.removeItem(APP_MEMBERSHIP_FORM)
      }
    },
  },
}
