'use strict';

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _searchNames = require('../constants/searchNames');

var _recordDataHelpers = require('../helpers/recordDataHelpers');

var _login = require('../actions/login');

var _logout = require('../actions/logout');

var _record = require('../actions/record');

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

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

/**
 * Generates a search key for a given search descriptor. All search descriptors that represent the
 * same search should have the same search key.
 */
const searchKey = exports.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.

  const pairs = (0, _objectHelpers.asPairs)(_immutable2.default.Map.isMap(searchDescriptor) ? searchDescriptor.toJS() : searchDescriptor);

  // Serialize the name/value pairs to JSON.

  return JSON.stringify(pairs);
};

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


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

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

  return state;
};

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


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

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

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

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

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

    const pageChanged = 'searchQuery.p' in changes;
    const sortChanged = 'searchQuery.sort' in changes;
    const 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 = updatedNamedSearch.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]);
      }

      delete changes['searchQuery.p'];
      delete changes['searchQuery.size'];
      delete changes['searchQuery.sort'];
      delete changes.seqID;

      if (Object.keys(changes).length > 0) {
        // Something other than page num, page size, sort, or seq id changed. Clear selected items.

        updatedNamedSearch = updatedNamedSearch.delete('selected');
      }
    }
  }

  // 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.

  const searchQuery = searchDescriptor.get('searchQuery');
  const p = searchQuery.get('p');
  const size = searchQuery.get('size');

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

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

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

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

const computeIndexesByCsid = (listTypeConfig, result) => {
  const listNodeName = listTypeConfig.listNodeName,
        itemNodeName = listTypeConfig.itemNodeName;


  let indexesByCsid;
  let items = result.getIn([listNodeName, itemNodeName]);

  if (items) {
    if (!_immutable2.default.List.isList(items)) {
      items = _immutable2.default.List.of(items);
    }

    indexesByCsid = _immutable2.default.Map(items.map((item, index) => [item.get('csid') || item.get('docId'), index]));
  }

  return indexesByCsid;
};

const setSearchResult = (state, listTypeConfig, searchName, searchDescriptor, result) => {
  const namedSearch = state.get(searchName);
  const key = searchKey(searchDescriptor);

  if (namedSearch && namedSearch.hasIn(['byKey', key])) {
    const itemNodeName = listTypeConfig.itemNodeName,
          listNodeName = listTypeConfig.listNodeName,
          normalizeListData = listTypeConfig.normalizeListData;


    const normalizedResult = normalizeListData ? normalizeListData(result, listTypeConfig) : result;

    const searchState = namedSearch.getIn(['byKey', key]);

    const updatedSearchState = searchState.set('isPending', false).set('result', normalizedResult).set('indexesByCsid', computeIndexesByCsid(listTypeConfig, normalizedResult)).set('listNodeName', listNodeName).set('itemNodeName', itemNodeName).delete('error');

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

    return state.set(searchName, updatedNamedSearch);
  }

  return state;
};

const handleCreateEmptySearchResult = (state, action) => {
  var _action$meta3 = action.meta;
  const listTypeConfig = _action$meta3.listTypeConfig,
        searchName = _action$meta3.searchName,
        searchDescriptor = _action$meta3.searchDescriptor;


  const searchQuery = searchDescriptor.get('searchQuery');
  const p = searchQuery.get('p');
  const size = searchQuery.get('size');

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

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

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

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


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

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


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

  if (namedSearch && namedSearch.hasIn(['byKey', key])) {
    const 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;
};

const handleSetAllResultItemsSelected = (state, action) => {
  const isSelected = action.payload;

  var _action$meta6 = action.meta;
  const filter = _action$meta6.filter,
        listTypeConfig = _action$meta6.listTypeConfig,
        searchName = _action$meta6.searchName,
        searchDescriptor = _action$meta6.searchDescriptor;
  const listNodeName = listTypeConfig.listNodeName,
        itemNodeName = listTypeConfig.itemNodeName;


  const namedSearch = state.get(searchName);

  if (namedSearch) {
    const key = searchKey(searchDescriptor);
    const path = ['byKey', key, 'result', listNodeName, itemNodeName];

    let items = namedSearch.getIn(path);

    if (!_immutable2.default.List.isList(items)) {
      items = _immutable2.default.List.of(items);
    }

    if (filter) {
      items = items.filter(filter);
    }

    const selectedItems = namedSearch.get('selected') || _immutable2.default.Map();

    let updatedSelectedItems;

    if (isSelected) {
      updatedSelectedItems = selectedItems.withMutations(map => items.reduce((updatedMap, item) => updatedMap.set(item.get('csid'), item), map));
    } else {
      updatedSelectedItems = selectedItems.withMutations(map => items.reduce((updatedMap, item) => updatedMap.delete(item.get('csid')), map));
    }

    return state.set(searchName, namedSearch.set('selected', updatedSelectedItems));
  }

  return state;
};

const handleSetResultItemSelected = (state, action) => {
  const isSelected = action.payload;

  var _action$meta7 = action.meta;
  const listTypeConfig = _action$meta7.listTypeConfig,
        searchName = _action$meta7.searchName,
        searchDescriptor = _action$meta7.searchDescriptor,
        index = _action$meta7.index;
  const listNodeName = listTypeConfig.listNodeName,
        itemNodeName = listTypeConfig.itemNodeName;


  const namedSearch = state.get(searchName);

  if (namedSearch) {
    const key = searchKey(searchDescriptor);
    const path = ['byKey', key, 'result', listNodeName, itemNodeName, index];
    const item = (0, _recordDataHelpers.deepGet)(namedSearch, path);

    const csid = item.get('csid');

    const updatedNamedSearch = isSelected ? namedSearch.setIn(['selected', csid], item) : namedSearch.deleteIn(['selected', csid]);

    return state.set(searchName, updatedNamedSearch);
  }

  return state;
};

const clearFilteredResults = (state, filter) => {
  let nextState = state;

  state.filter(filter).forEach((searchState, searchName) => {
    nextState = nextState.delete(searchName);
  });

  return nextState;
};

const clearNamedResults = (state, action) => state.delete(action.meta.searchName);

const clearAllResults = state => state.clear();

const handleRecordDeleteFulfilled = state => clearAllResults(state);

const handleRecordTransitionFulfilled = (state, action) => {
  const transitionName = action.meta.transitionName;


  if (transitionName === 'delete') {
    return clearAllResults(state);
  }

  return state;
};

const handleLoginFulfilled = (state, action) => {
  var _action$meta8 = action.meta;
  const prevUsername = _action$meta8.prevUsername,
        username = _action$meta8.username;


  if (prevUsername !== username) {
    // The logged in user has changed. Remove all search state, because the new user may not be
    // permitted to list some records that the previous user could.

    return clearAllResults(state);
  }

  return state;
};

exports.default = (state = _immutable2.default.Map(), action) => {
  switch (action.type) {
    case _search.CLEAR_SELECTED:
      return state.deleteIn([action.meta.searchName, 'selected']);
    case _search.CLEAR_SEARCH_RESULTS:
      return clearNamedResults(state, action);
    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);
    case _search.SET_ALL_RESULT_ITEMS_SELECTED:
      return handleSetAllResultItemsSelected(state, action);
    case _search.SET_RESULT_ITEM_SELECTED:
      return handleSetResultItemSelected(state, action);
    case _search.DESELECT_RESULT_ITEM:
      return state.deleteIn([action.meta.searchName, 'selected', action.meta.csid]);
    case _record.SUBRECORD_CREATED:
      return clearNamedResults(state, action);
    case _record.RECORD_CREATED:
      // We don't really know which search results will be affected by a record being created, so
      // clear them all -- except for the report and batch panels, which should not ever be
      // affected by a record being created.

      return clearFilteredResults(state, (searchState, searchName) => searchName !== _searchNames.RECORD_BATCH_PANEL_SEARCH_NAME && searchName !== _searchNames.RECORD_REPORT_PANEL_SEARCH_NAME);
    case _record.RECORD_DELETE_FULFILLED:
      return handleRecordDeleteFulfilled(state, action);
    case _record.RECORD_TRANSITION_FULFILLED:
      return handleRecordTransitionFulfilled(state, action);
    case _login.LOGIN_FULFILLED:
      return handleLoginFulfilled(state, action);
    case _logout.LOGOUT_FULFILLED:
      return clearAllResults(state);
    default:
      return state;
  }
};

const isPending = exports.isPending = (state, searchName, searchDescriptor) => state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'isPending']);

const getState = exports.getState = (state, searchName, searchDescriptor) => state.getIn([searchName, 'byKey', searchKey(searchDescriptor)]);

const getIndexesByCsid = exports.getIndexesByCsid = (state, searchName, searchDescriptor) => state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'indexesByCsid']);

const getMostRecentDescriptor = exports.getMostRecentDescriptor = (state, searchName) => state.getIn([searchName, 'byKey', state.getIn([searchName, 'mostRecentKey']), 'descriptor']);

const getResult = exports.getResult = (state, searchName, searchDescriptor) => state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'result']);

const getError = exports.getError = (state, searchName, searchDescriptor) => state.getIn([searchName, 'byKey', searchKey(searchDescriptor), 'error']);

const getSelectedItems = exports.getSelectedItems = (state, searchName) => state.getIn([searchName, 'selected']);