import _ from 'lodash'
import resolver from '@/helpers/masterDataResolver'

/**
 * Maps master data values to id
 *
 * @example
 * computed: {
 *   ...mapMasterDataId({
 *        'SALE_DELIVERY_METHOD': {
 *          deliveryId: 'DELIVERY',
 *          selfPickupId: 'SELF_PICKUP'
 *        },
 *        'SALE_TYPES': {
 *          salesTypeRegistrationId: 'REGISTRATION',
 *          salesTypeFormationId: 'FORMATION'
 *        }
 *      })
 * }
 *
 *  // usage in components
 *  this.salesTypeRegistrationId
 *
 *  // usage in template
 *  {{ salesTypeRegistrationId }}
 *
 *  // usage in waiting for loading
 *  this.resolveMasters.then(() => { console.log(this.salesTypeRegistrationId) })
 *
 * @param mappings
 * @param countryIdGetterName only accept getters
 * @returns {function}
 */
export default (mappings, countryIdGetterName = false) => {
  let functions = {}
  let keys = _.keys(mappings)

  // general resolver
  functions['resolveMasters'] = resolver
  // master key resolver
  functions['_masterKeyIdsToResolve'] = function() {
    return keys
  }
  functions['_masterCountryGetterName'] = function() {
    return countryIdGetterName
  }
  keys.forEach(key => {
    for (let method in mappings[key]) {
      functions[method] = function() {
        this['resolveMasters']
        let masterKey = this.$const.masterKey[key] || key

        if (mappings[key][method] === 'options') {
          return this.$store.getters.getMasterDataOptionsByKey(masterKey)
        }
        return this.$store.getters['getMasterDataIdByKeyAndTitle'](
          masterKey,
          this.$const.masterData[mappings[key][method]] || mappings[key][method]
        )
      }
    }
  })
  return functions
}
