import { List } from 'immutable';

import { fetchItems as fetchItemsApi } from '../api/items.js';
import {
  GET_ITEMS,
  ITEMS_LOADED,
} from '../constants/actionTypes.js';
import { getActiveEventId } from '../selectors/activeEvent.js';
import { getAuthToken } from '../selectors/auth.js';

import { blockUI, unblockUI } from './index.js';

import Item from '../domain/Item.js';

const itemsLoaded = (payload) => ({ type: ITEMS_LOADED, payload });

const itemsLoadError = (payload) => ({ type: ITEMS_LOAD_FAILED, payload });

const itemsFetchSuccess = (items) => (dispatch) => {
  const payload = List(items).map((i) => Item.fromJS(i));

  dispatch(itemsLoaded(payload));
  dispatch(unblockUI);
};

const itemsFetchFailure = (error) => (dispatch) => {
  console.error('[actions::items::itemsFetchFailure]', error);
  dispatch(itemsLoadFailure(error));
  dispatch(unblockUI);
};

export const fetchItems = () => (dispatch, getState) => {
  const eventId = getActiveEventId(getState());
  const authToken = getAuthToken(getState());

  fetchItemsApi(activeEvent, authToken)
    .then(payload => dispatch(itemsFetchSuccess(payload)))
    .catch(err => dispatch(itemsFetchFailure(err)));
};
