import { combineReducers } from 'redux'
import locationReducer from './location'
import apiDataReducer from 'modules/api_data/reducers'
import userSessionReducer from 'modules/user_session/reducers'
import metricsDataReducer from 'modules/metrics_data/reducers'

export const RESET_APP_STATE = 'RESET_APP_STATE'

export function resetAppState () {
  return {
    type: RESET_APP_STATE
  }
}

export function resetAppStateExcept (...keys) {
  return {
    type: RESET_APP_STATE,
    keys: keys
  }
}

const makeRootReducer = asyncReducers => {
  const appReducer = combineReducers({
    location: locationReducer,
    api_data: apiDataReducer,
    user_session: userSessionReducer,
    metrics_data: metricsDataReducer,
    ...asyncReducers
  })
  return (state, action) => {
    if (action.type === RESET_APP_STATE) {
      let newState = {}
      if (action.keys !== undefined) {
        action.keys.forEach((key) => {
          newState[key] = state[key]
        })
      }
      state = newState
    }
    return appReducer(state, action)
  }
}

export const injectReducer = (store, { key, reducer }) => {
  if (Object.hasOwnProperty.call(store.asyncReducers, key)) return

  store.asyncReducers[key] = reducer
  store.replaceReducer(makeRootReducer(store.asyncReducers))
}

export default makeRootReducer
