import omit from 'lodash/omit';
import { getId, arrayify, getNodeMap } from '../utils/jsonld';
import {
  FETCH_GALLERIES,
  FETCH_GALLERIES_SUCCESS,
  FETCH_GALLERIES_ERROR,
  CREATE_GALLERY_SUCCESS,
  UPDATE_GALLERY_SUCCESS,
  DELETE_GALLERY_SUCCESS
} from '../actions/gallery-action-creators';
import {
  CREATE_WORK_SUCCESS,
  DELETE_WORK_SUCCESS
} from '../actions/work-action-creators';

export function galleryMap(state = {}, action) {
  switch (action.type) {
    case FETCH_GALLERIES_SUCCESS:
      return action.payload.reduce((galleryMap, gallery) => {
        galleryMap[getId(gallery)] = gallery;
        return galleryMap;
      }, {});

    case CREATE_WORK_SUCCESS:
    case CREATE_GALLERY_SUCCESS:
    case UPDATE_GALLERY_SUCCESS: {
      const gallery = arrayify(action.payload.result).find(
        result => result['@type'] === 'Gallery'
      );
      return Object.assign({}, state, {
        [getId(gallery)]: gallery
      });
    }

    case DELETE_WORK_SUCCESS: {
      const galleries = arrayify(action.payload.result).filter(
        result => result['@type'] === 'Gallery'
      );
      return Object.assign({}, state, getNodeMap(galleries));
    }

    case DELETE_GALLERY_SUCCESS:
      return omit(state, [action.meta.galleryId]);

    default:
      return state;
  }
}

export function fetchGalleriesStatus(
  state = { isActive: false, error: null },
  action
) {
  switch (action.type) {
    case FETCH_GALLERIES:
      return { isActive: true, error: null };

    case FETCH_GALLERIES_SUCCESS:
      return { isActive: false, error: null };

    case FETCH_GALLERIES_ERROR:
      return { isActive: false, error: action.error };

    default:
      return state;
  }
}
