'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getMatches = getMatches;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _partialTermSearch = require('../actions/partialTermSearch');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = (state = _immutable2.default.Map(), action) => {
  let count;
  let items;

  switch (action.type) {
    case _partialTermSearch.ADD_TERM_STARTED:
      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        isAddPending: true
      }));
    case _partialTermSearch.ADD_TERM_FULFILLED:
      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        newTerm: _immutable2.default.fromJS(action.payload.data)
      }));
    case _partialTermSearch.ADD_TERM_REJECTED:
      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        error: action.payload
      }));
    case _partialTermSearch.PARTIAL_TERM_SEARCH_STARTED:
      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        isSearchPending: true
      }));
    case _partialTermSearch.PARTIAL_TERM_SEARCH_FULFILLED:
      count = parseInt(action.payload.data['ns2:abstract-common-list'].itemsInPage, 10);

      if (isNaN(count) || count === 0) {
        items = [];
      } else {
        items = action.payload.data['ns2:abstract-common-list']['list-item'];

        if (!Array.isArray(items)) {
          items = [items];
        }
      }

      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        items
      }));
    case _partialTermSearch.PARTIAL_TERM_SEARCH_REJECTED:
      return state.setIn([action.meta.partialTerm, action.meta.recordType, action.meta.vocabulary], _immutable2.default.Map({
        error: action.payload
      }));
    case _partialTermSearch.CLEAR_PARTIAL_TERM_SEARCH_RESULTS:
      return state.clear();
    default:
      return state;
  }
};

function getMatches(state) {
  return state;
}