import { applyMiddleware, compose, createStore, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { STORE_REPLACE } from './Constant';

function getReducers(stores) {
  const reducers = {};
  stores.forEach(item => {
    if (reducers[item.key]) return;
    reducers[item.key] = item.handle.bind(item);
  });
  return reducers;
}
function initReducers(stores, project, services) {
  stores.forEach(item => {
    item.init.bind(item)(project, services);
  });
}
function setReducersStore(store, stores) {
  stores.forEach(item => {
    item.setStore.bind(item)(store);
  });
}
// redux 基本配置
export function initStore(initState, stores, project, services) {
  initReducers(stores, project, services);
  const middleware = [thunk];
  const composeEnhancers = __DEBUG__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose : compose;
  const cr = combineReducers(getReducers(stores));
  const ce = composeEnhancers(applyMiddleware(...middleware));
  const store = createStore(cr, initState, ce);
  setReducersStore(store, stores);
  return store;
}
export function refreshStore(store, stores, project, services) {
  initReducers(stores, project, services);
  store.replaceReducer(combineReducers(getReducers(stores)));
  setReducersStore(store, stores);
  store.dispatch({ type: STORE_REPLACE });
}
