import rootReducer from '../reducers';
import rootAuthSaga from '../sagas/authSaga';
import networkSaga from '../sagas/networkSaga';
import { compose, createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga'
import Immutable from 'immutable';
import { offline } from 'redux-offline';
import offlineDefaultConfig from 'redux-offline/lib/defaults';
import localForage from 'localforage';
import immutableTransform from 'redux-persist-transform-immutable';
import NoteRecord from './noteRecord';
import SessionRecord from './sessionRecord';
import UserRecord from './userRecord';
import APIClient from '../api/APIClient';
import createEffect from '../api';
import config from '../config';
import { offlineConfigInitialized } from '../actions/networkActions';
// const composeEnhancers = (process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ?
// window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// shouldHotReload: false,
// }) : compose;
const composeEnhancers = compose;
const defaultState = {
sessions: Immutable.List([]),
notes: Immutable.List([]),
isAuthenticated: false,
currentUser: null,
token: '',
autoSubmit: false,
login: Immutable.Map({
loading: false,
success: false,
error: false,
})
};
const immutableTransformConfig = {
records: [NoteRecord, SessionRecord, UserRecord],
whitelist: ['sessions', 'notes', 'currentUser']
}
const persistOptions = {
storage: localForage,
transforms: [immutableTransform(immutableTransformConfig)],
whitelist: ['sessions', 'notes', 'isAuthenticated', 'currentUser', 'token', 'offline', 'autoSubmit']
}
const apiClient = new APIClient(config.apiRootUrl);
const offlineConfig = {
...offlineDefaultConfig,
persistOptions,
effect: createEffect(apiClient),
}
const storeInitialState = { ...defaultState };
export default (history, initialState = storeInitialState) => {
const router = routerMiddleware(history);
const saga = createSagaMiddleware();
offlineConfig.detectNetwork = callback => { saga.run(networkSaga, { callback }); };
const store = offline(offlineConfig)(createStore)(rootReducer, initialState, composeEnhancers(
applyMiddleware(router, saga)
));
apiClient.setStore(store);
const context = {
client: apiClient,
history
}
saga.run(rootAuthSaga, context);
store.dispatch(offlineConfigInitialized({ client: apiClient }))
return store;
};