import _ from 'lodash'
import resolver from '@/helpers/masterDataResolver'
/**
 * Maps master data key list to local variable
 *
 * @example
 * // map gender list to local variable
 * computed
 * ...mapMasterDataKey({
 *    shippingDeliveryMethods: 'SALE_DELIVERY_METHOD'
 *  })
 *
 *  // usage in components
 *  this.shippingDeliveryMethods
 *
 *  // usage in template
 *  {{shippingDeliveryMethods}}
 *
 *  // usage in waiting for loading
 *  let self = this
 *  this.resolveMasters.then(() => { console.log(this.shippingDeliveryMethods) })
 *
 * @param mappings
 * @param countryIdGetterName only accept getters
 * @returns {function}
 */
export default (mappings, countryIdGetterName = false) => {
  let functions = {}
  let keys = _.keys(mappings)
  let masterDataKeys = _.values(mappings)
  // general resolver
  functions['resolveMasters'] = resolver
  // master key resolver
  functions['_masterKeysToResolve'] = function() {
    return masterDataKeys
  }
  functions['_masterCountryGetterName'] = function() {
    return countryIdGetterName
  }
  // mapping keys
  keys.forEach(key => {
    functions[key] = function() {
      this['resolveMasters']
      return this.$store.getters['getMasterDataByKey'](this.$const.masterKey[mappings[key]] || mappings[key])
    }
  })
  return functions
}
