import _ from 'lodash'

export default {
  isLoading: state => process => {
    return process.constructor === Array
      ? process.findIndex(loading => state.loading.indexOf(loading) !== -1) !== -1
      : state.loading.indexOf(process) !== -1
  },
  hasLoaded: state => process => {
    if (process.constructor === Array) {
      return process.every(pwd => pwd.indexOf(pwd) !== -1)
    }
    return state.loaded.indexOf(process) !== -1
  },
  afterLoading: state => process => {
    if (typeof state.loadingPromises[process] === 'undefined') {
      state.loadingPromises[process] = new Promise((resolve, reject) => {
        state.loadingPromisesResolvers[process] = resolve
      })
    }
    if (state.loaded.indexOf(process) !== -1) {
      state.loadingPromisesResolvers[process](true)
    }
    return state.loadingPromises[process]
  },
  getCachedLoad: state => (name, payload) => {
    let cache = state.cacheLoads[name]

    if (cache) {
      return _.find(cache, ['payload', payload])
    }

    return false
  },
}
