import { List } from 'immutable';

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

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

const beginItemLoad = () => ({ type: GET_ITEMS });

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

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

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

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

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

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