import { PROCESSING_STARTED, PROCESSING_FINISHED, SET_CACHED_LOADING } from '../../utils/types'
import Vue from 'vue'

export default {
  [PROCESSING_STARTED](state, process) {
    state.loading.push(process)
    var loadedIndex = state.loaded.indexOf(process)
    if (loadedIndex !== -1) {
      state.loaded.splice(loadedIndex, 1)
    }
    if (typeof state.loadingPromises[process] === 'undefined') {
      state.loadingPromises[process] = new Promise((resolve, reject) => {
        state.loadingPromisesResolvers[process] = resolve
      })
    }
  },
  [PROCESSING_FINISHED](state, process) {
    var index = state.loading.indexOf(process)
    if (index !== -1) {
      state.loading.splice(index, 1)
    }
    if (state.loaded.indexOf(process) === -1) {
      state.loaded.push(process)
    }
    if (typeof state.loadingPromises[process] !== 'undefined') {
      Vue.prototype.$nextTick(() => {
        state.loadingPromisesResolvers[process](true)
      })
    }
  },
  [SET_CACHED_LOADING](state, payload) {
    if (!state.cacheLoads[payload.name]) {
      state.cacheLoads[payload.name] = []
    }
    state.cacheLoads[payload.name].push(payload)
  },
}
