
import thunk from 'redux-thunk';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { authReducer, promiseReducer, cartReducer, promiseImg, upLoaderReducer } from '../reducer';
import { actionRootCats } from '../action';

const localStoredReducer = (reducer, localStorageName) =>
  (state, action) => {
    if (!state) {
      const key = localStorage.getItem(localStorageName);
      if (key) {
        return JSON.parse(key);
      } else {
        return reducer(state, action);
      }
    }
    if (state) {
      const newState = reducer(state, action);
      localStorage.setItem(localStorageName, JSON.stringify(newState));
      return newState;
    }
  };

export const store = createStore(combineReducers({
  promise: localStoredReducer(promiseReducer, 'promise'),
  auth: localStoredReducer(authReducer, 'auth'),
  cart: localStoredReducer(cartReducer, 'cart'),
  img: localStoredReducer(promiseImg, 'img'),
  upLoad: localStoredReducer(upLoaderReducer, 'upLoad')
}), applyMiddleware(thunk));

store.subscribe(() => console.log(store.getState()));
store.dispatch(actionRootCats());
