'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.searchKey = undefined;
exports.isPending = isPending;
exports.getResult = getResult;
exports.getError = getError;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _objectHelpers = require('../helpers/objectHelpers');

var _search = require('../actions/search');

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * Generates a search key for a given search descriptor. All search descriptors that represent the
 * same search should have the same search key.
 */
var searchKey = exports.searchKey = function searchKey(searchDescriptor) {
  // First convert the search descriptor to an array of name/value pairs, sorted by name. This
  // ensures that the key is not sensitive to the order in which properties are iterated out of the
  // search descriptor object.

  var pairs = (0, _objectHelpers.asPairs)(searchDescriptor);

  // Serialize the name/value pairs to JSON.

  return JSON.stringify(pairs);
};

var handleSetMostRecentSearch = function handleSetMostRecentSearch(state, action) {
  var _action$meta = action.meta,
      searchName = _action$meta.searchName,
      searchDescriptor = _action$meta.searchDescriptor;


  var key = searchKey(searchDescriptor);
  var namedSearch = state.get(searchName);

  if (namedSearch && namedSearch.getIn(['byKey', key])) {
    return state.set(searchName, namedSearch.set('mostRecentKey', key));
  }

  return state;
};

var handleSearchStarted = function handleSearchStarted(state, action) {
  var _action$meta2 = action.meta,
      listTypeConfig = _action$meta2.listTypeConfig,
      searchName = _action$meta2.searchName,
      searchDescriptor = _action$meta2.searchDescriptor;
  var listNodeName = listTypeConfig.listNodeName,
      itemNodeName = listTypeConfig.itemNodeName;


  var namedSearch = state.get(searchName) || _immutable2.default.Map();

  var key = searchKey(searchDescriptor);
  var mostRecentKey = namedSearch.get('mostRecentKey');

  var updatedNamedSearch = namedSearch;
  var result = null;
  var itemsInPage = null;
  var totalItems = null;
  var items = null;

  if (mostRecentKey) {
    var mostRecentSearchState = namedSearch.getIn(['byKey', mostRecentKey]);
    var mostRecentSearchDescriptor = mostRecentSearchState.get('descriptor');

    var changes = (0, _objectHelpers.diff)(searchDescriptor, mostRecentSearchDescriptor.toJS());
    var changeCount = Object.keys(changes).length;

    var pageChanged = 'searchQuery.p' in changes;
    var sortChanged = 'searchQuery.sort' in changes;
    var seqIDChanged = 'seqID' in changes;

    if (pageChanged && changeCount === 1) {
      // Only the page number changed from the last search. Seed these results with the total items
      // count from the previous results, since it probably will remain the same. This allows the
      // UI to render a smooth transition from this page to the next, without the count information
      // and pager blinking out.

      totalItems = mostRecentSearchState.getIn(['result', listNodeName, 'totalItems']);
    } else {
      // Something other than the page number changed from the last search. Clear out stored
      // search states. (If only the page number changed, keep the previous states around as a
      // cache so that flipping between pages will be fast.)

      updatedNamedSearch = namedSearch.set('byKey', _immutable2.default.Map());

      if (sortChanged && changeCount === 1) {
        // Only the sort changed from the last search. As above, seed these results with the total
        // items count. Also seed the itemsInPage count, since this is not expected to change.

        totalItems = mostRecentSearchState.getIn(['result', listNodeName, 'totalItems']);

        itemsInPage = mostRecentSearchState.getIn(['result', listNodeName, 'itemsInPage']);
      } else if (seqIDChanged && changeCount === 1) {
        // Only the seq id changed from the last search. This means that the search parameters
        // themselves haven't changed, but the search is being triggered because the data may have
        // changed. Seed the result with the previous total items, items in page, and items. This
        // makes for the smoothest possible transition to the new result set.

        totalItems = mostRecentSearchState.getIn(['result', listNodeName, 'totalItems']);

        itemsInPage = mostRecentSearchState.getIn(['result', listNodeName, 'itemsInPage']);

        items = mostRecentSearchState.getIn(['result', listNodeName, itemNodeName]);
      }
    }
  }

  // Seed the search state with a blank result that has the page num and size of this search, and
  // the total items and items in page counts from the last search, if they're not expected to
  // change. This allows a blank result table to be rendered while the search is pending,
  // preventing a flash of empty content.

  var _searchDescriptor$sea = searchDescriptor.searchQuery,
      p = _searchDescriptor$sea.p,
      size = _searchDescriptor$sea.size;


  var pageNum = typeof p === 'number' ? p.toString() : p;
  var pageSize = typeof size === 'number' ? size.toString() : size;

  result = _immutable2.default.fromJS(_defineProperty({}, listNodeName, _defineProperty({
    itemsInPage: itemsInPage,
    totalItems: totalItems,
    pageNum: pageNum,
    pageSize: pageSize
  }, itemNodeName, items)));

  updatedNamedSearch = updatedNamedSearch.set('mostRecentKey', key).setIn(['byKey', key], _immutable2.default.fromJS({
    result: result,
    descriptor: searchDescriptor,
    isPending: true
  }));

  return state.set(searchName, updatedNamedSearch);
};

var setSearchResult = function setSearchResult(state, searchName, searchDescriptor, result) {
  var namedSearch = state.get(searchName);
  var key = searchKey(searchDescriptor);

  if (namedSearch && namedSearch.hasIn(['byKey', key])) {
    var searchState = namedSearch.getIn(['byKey', key]);

    var updatedSearchState = searchState.set('isPending', false).set('result', result).delete('error');

    var updatedNamedSearch = namedSearch.setIn(['byKey', key], updatedSearchState);

    return state.set(searchName, updatedNamedSearch);
  }

  return state;
};

var handleCreateEmptySearchResult = function handleCreateEmptySearchResult(state, action) {
  var _action$meta3 = action.meta,
      listTypeConfig = _action$meta3.listTypeConfig,
      searchName = _action$meta3.searchName,
      searchDescriptor = _action$meta3.searchDescriptor;
  var _searchDescriptor$sea2 = searchDescriptor.searchQuery,
      p = _searchDescriptor$sea2.p,
      size = _searchDescriptor$sea2.size;


  var pageNum = typeof p === 'number' ? p.toString() : p;
  var pageSize = typeof size === 'number' ? size.toString() : size;

  var result = _immutable2.default.fromJS(_defineProperty({}, listTypeConfig.listNodeName, {
    itemsInPage: '0',
    totalItems: '0',
    pageNum: pageNum,
    pageSize: pageSize
  }));

  return setSearchResult(state, searchName, searchDescriptor, result);
};

var handleSearchFulfilled = function handleSearchFulfilled(state, action) {
  var _action$meta4 = action.meta,
      searchName = _action$meta4.searchName,
      searchDescriptor = _action$meta4.searchDescriptor;


  return setSearchResult(state, searchName, searchDescriptor, _immutable2.default.fromJS(action.payload.data));
};

var handleSearchRejected = function handleSearchRejected(state, action) {
  var _action$meta5 = action.meta,
      searchName = _action$meta5.searchName,
      searchDescriptor = _action$meta5.searchDescriptor;


  var namedSearch = state.get(searchName);
  var key = searchKey(searchDescriptor);

  if (namedSearch && namedSearch.hasIn(['byKey', key])) {
    var updatedNamedSearch = namedSearch.setIn(['byKey', key], namedSearch.getIn(['byKey', key]).set('isPending', false).set('error', _immutable2.default.fromJS(action.payload)).delete('result'));

    return state.set(searchName, updatedNamedSearch);
  }

  return state;
};

exports.default = function () {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _immutable2.default.Map();
  var action = arguments[1];

  switch (action.type) {
    case _search.SET_MOST_RECENT_SEARCH:
      return handleSetMostRecentSearch(state, action);
    case _search.CREATE_EMPTY_SEARCH_RESULT:
      return handleCreateEmptySearchResult(state, action);
    case _search.SEARCH_STARTED:
      return handleSearchStarted(state, action);
    case _search.SEARCH_FULFILLED:
      return handleSearchFulfilled(state, action);
    case _search.SEARCH_REJECTED:
      return handleSearchRejected(state, action);
    default:
      return state;
  }
};

function isPending(state, searchName, searchDescriptor) {
  return state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'isPending']);
}

function getResult(state, searchName, searchDescriptor) {
  return state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'result']);
}

function getError(state, searchName, searchDescriptor) {
  return state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'error']);
}