import { ADD_MASTER_KEYS, ADD_MASTER_KEYS_ENROLEMENT } from '../../utils/types'
import { post } from '../../utils/api'
import { MASTER_KEY_URL } from '../../utils/apiUrls'
import constants from '@/config/const'

export const loadMasterDataKeys = async ({ commit, dispatch, rootGetters }, payload) => {
  let cancelToken = await dispatch('generateCancelToken', `materKey-${payload ? JSON.stringify(payload) : 'null'}`, {
    root: true,
  })
  let country_id = null
  if (payload.masterCountryGetterName !== undefined && Array.isArray(payload.keys)) {
    if (payload.masterCountryGetterName !== false) {
      if (typeof payload.masterCountryGetterName === 'object') {
        if (rootGetters[payload.masterCountryGetterName.name] !== undefined) {
          country_id = rootGetters[payload.masterCountryGetterName.name][payload.masterCountryGetterName.key]
        }
      } else {
        if (rootGetters[payload.masterCountryGetterName] !== undefined) {
          country_id = rootGetters[payload.masterCountryGetterName]
        }
      }
    }
    payload = { keys: payload.keys }
    if (country_id !== null) {
      payload['country_id'] = country_id
    }
  } else {
    // Todo temp remove once all master data request converted to mixin
    if (Array.isArray(payload)) {
      payload = { keys: payload }
    }
  }
  return dispatch('loadCached', {
    loaderName: 'loadMasterDataKeys',
    payload: payload,
  }).then(load => {
    if (load) {
      return post(MASTER_KEY_URL, payload, cancelToken.token).then(response => {
        commit(ADD_MASTER_KEYS, response.data)
      })
    }
  })
}

export const loadMasterDataKeysEnrolment = async ({ commit }, query) => {
  return await post(MASTER_KEY_URL, query).then(response => {
    commit(ADD_MASTER_KEYS_ENROLEMENT, response.data)
  })
}

export const loadFetchMasterDataKeys = async ({ commit, dispatch, getters }, masterKeyConst) => {
  if (!getters.getMasterDataByKey(constants.masterKey[masterKeyConst])) {
    await dispatch('loadMasterDataKeys', [constants.masterKey[masterKeyConst]])
  }
  return getters.getMasterDataByKey(constants.masterKey[masterKeyConst])
}

export const loadFetchMasterDataId = async ({ commit, dispatch, getters }, payload) => {
  await dispatch('loadFetchMasterDataKeys', payload.master)
  return getters.getMasterDataIdByKeyAndTitle(constants.masterKey[payload.master], constants.masterData[payload.data])
}
