import router from '@/router'

const savedHiddenColumnKeysMap = JSON.parse(localStorage.getItem('savedHiddenColumnKeysMap') ?? '{}')
const savedTableFilterValuesMap = JSON.parse(localStorage.getItem('savedTableFilterValuesMap') ?? '{}')
const savedFormDataMap = JSON.parse(localStorage.getItem('savedFormDataMap') ?? '{}')

const state = {
  savedHiddenColumnKeysMap,
  savedTableFilterValuesMap,
  savedFormDataMap
}

const mutations = {
  SAVE_HIDDEN_COLUMN_KEYS(state, { keys, tableName }) {
    const fullTableName = router.currentRoute.name + (tableName ? `/${tableName}` : '')
    state.savedHiddenColumnKeysMap = {
      ...state.savedHiddenColumnKeysMap,
      [fullTableName]: keys
    }
    localStorage.setItem('savedHiddenColumnKeysMap', JSON.stringify(state.savedHiddenColumnKeysMap))
  },
  SAVE_TABLE_FILTER_VALUES(state, { filterValues, tableName }) {
    const fullTableName = router.currentRoute.name + (tableName ? `/${tableName}` : '')
    state.savedTableFilterValuesMap = {
      ...state.savedTableFilterValuesMap,
      [fullTableName]: filterValues
    }
    localStorage.setItem('savedTableFilterValuesMap', JSON.stringify(state.savedTableFilterValuesMap))
  },
  SAVE_FORM_DATA(state, { formData, formName }) {
    const fullFormName = router.currentRoute.name + (formName ? `/${formName}` : '')
    state.savedFormDataMap = {
      ...state.savedFormDataMap,
      [fullFormName]: formData
    }
    localStorage.setItem('savedFormDataMap', JSON.stringify(state.savedFormDataMap))
  }
}

const actions = {
  saveHiddenColumnKeys({ commit }, payload) {
    commit('SAVE_HIDDEN_COLUMN_KEYS', payload)
  },
  saveTableFilterValues({ commit }, payload) {
    commit('SAVE_TABLE_FILTER_VALUES', payload)
  },
  saveFormData({ commit }, payload) {
    commit('SAVE_FORM_DATA', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
