/*
 *
 * FetchData reducer
 *
 */

import { fromJS } from 'immutable'
import { FETCH, FETCH_SUCCESS, FETCH_FAILURE } from './constants'

const initialState = fromJS({})

const setState = (state, requestKey, payload) => {
  return state.update(requestKey, (data) => {
    return data.merge(fromJS(payload))
  })
}

function fetchDataReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH: {
      const payload = {
        isLoading: true,
      }
      return setState(state, action.requestKey, payload)
    }
    case FETCH_SUCCESS: {
      const payload = {
        resource: action.response,
        isLoading: false,
        error: null,
      }
      return setState(state, action.requestKey, payload)
    }
    case FETCH_FAILURE: {
      const payload = {
        isLoading: false,
        error: action.error,
      }
      return setState(state, action.requestKey, payload)
    }
    default:
      return state
  }
}

export default fetchDataReducer
