import { resolve, reject } from 'redux-simple-promise';
import * as fetchConstants from './fetchConstants.js';

// TODO: replace this with normalizr? https://github.com/gaearon/normalizr
export function arrayToDict(arr, keyPropertyName) {
  const dict = {};
  arr.forEach((item) => {
    dict[item[keyPropertyName]] = item;
  });
  return dict;
}

export function createAsyncReducer(handlers) {
  const initialState = {
    fetchStatus: fetchConstants.FETCH_INVALID,
    ...handlers.initialState,
  };
  return (state = initialState, action) => {
    switch (action.type) {
      case handlers.action:
        return Object.assign({}, state, {
          ...state,
          fetchStatus: fetchConstants.FETCH_ONGOING,
          ...handlers.handleFetch(action.payload),
        });
      case resolve(handlers.action):
        return Object.assign({}, state, {
          ...state,
          fetchStatus: fetchConstants.FETCH_SUCCEEDED,
          ...handlers.handleSuccess(action.payload),
        });
      case reject(handlers.action):
        return Object.assign({}, state, {
          ...state,
          fetchStatus: fetchConstants.FETCH_FAILED,
          ...handlers.handleFailure(action.payload),
        });
      default:
        return state;
    }
  };
}

@@ -495,16 +495,298 @@
 e,%0A  %7D;%0A
+  const reducers = %7B%7D;%0A  const asyncCallbackNames = %5B'handleFetch', 'handleSuccess', 'handleFetch'%5D;%0A  asyncCallbackNames.forEach((name) =%3E %7B%0A    if (handlers.hasOwnProperty(name)) %7B%0A      reducers%5Bname%5D = handlers%5Bname%5D;%0A    %7D else %7B%0A      reducers%5Bname%5D = () =%3E (%7B%7D);%0A    %7D%0A  %7D);%0A
   return
@@ -818,24 +818,24 @@
 ction) =%3E %7B%0A
-
     switch (
@@ -997,37 +997,37 @@
 G,%0A          ...
-handl
+reduc
 ers.handleFetch(
@@ -1214,37 +1214,37 @@
 D,%0A          ...
-handl
+reduc
 ers.handleSucces
@@ -1433,29 +1433,29 @@
          ...
-handl
+reduc
 ers.handleFa

make async reducer helped callbacks optional (defaulting to empty)