import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { all } from 'redux-saga/effects';

import reducerRegistry from '~/Utils/reducerRegistry';
import sagaRegistry from '~/Utils/sagaRegistry';
import { composeWithDevTools } from 'redux-devtools-extension';

import GlobalReducers from '~/GlobalReducers'

export default function configureStore(preloadedState = {}) {

  const sagaMiddleware = createSagaMiddleware();
  const middlewares = [sagaMiddleware];

  // preserve preloadedState for not-yet-loaded reducers
  const combine = reducers => {
    const reducerNames = Object.keys(reducers);
    Object.keys(preloadedState).forEach(item => {
      console.log('reducer : ' + item);
      if (reducerNames.indexOf(item) === -1) {
        reducers[item] = (state = null) => state;
      }
    });
    return combineReducers(reducers);
  };

  const reducer = combine({
    ...GlobalReducers,
    ...reducerRegistry.getReducers(),
  });

  const store = createStore(
    reducer,
    preloadedState,
    (__DEV__ ?
      composeWithDevTools(
        applyMiddleware(...middlewares)
      ) 
      :
      applyMiddleware(...middlewares)
    ),
  );

  const combineSaga = sagas => {
    const sagaNames = Object.keys(sagas);
    return sagaNames.map(x => sagas[x]());
  };

  function* rootSaga() {
    yield all(combineSaga(sagaRegistry.getSagas()));
  }
  sagaMiddleware.run(rootSaga);

  return store;
}
