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

/**
 * Maps master data values to id or key pass object
 *
 * @example
 * computed: {
 *   ...mapMasterData({
 *        'SALE_DELIVERY_METHOD': { // Standard
 *          deliveryId: 'DELIVERY',
 *          selfPickupId: 'SELF_PICKUP'
 *        },
 *        PRODUCT_AND_KITTING_FILTERS: { // Advance
 *          autoshipFilterKey: { name: 'PRODUCT_FILTER_AUTOSHIP', type: 'key' },
 *        },
 *      })
 * }
 *
 *  // 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 itemName = mappings[key][method]
        let itemKey = 'id'
        if (typeof mappings[key][method] === 'object') {
          itemName = mappings[key][method].name
          itemKey = mappings[key][method].type
        }
        if (itemKey === 'id') {
          return this.$store.getters['getMasterDataIdByKeyAndTitle'](
            this.$const.masterKey[key] || key,
            this.$const.masterData[itemName] || itemName
          )
        }
        if (itemKey === 'key') {
          return this.$store.getters['getMasterDataItemKeyByKeyAndId'](
            this.$const.masterKey[key] || key,
            this.$store.getters['getMasterDataIdByKeyAndTitle'](
              this.$const.masterKey[key] || key,
              this.$const.masterData[itemName] || itemName
            )
          )
        }
      }
    }
  })
  return functions
}
