'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.deselectResultItem = exports.setAllResultItemsSelected = exports.setResultItemSelected = exports.search = exports.clearSearchResults = exports.clearSelected = exports.DESELECT_RESULT_ITEM = exports.SET_RESULT_ITEM_SELECTED = exports.SET_ALL_RESULT_ITEMS_SELECTED = exports.SEARCH_REJECTED = exports.SEARCH_FULFILLED = exports.SEARCH_STARTED = exports.CREATE_EMPTY_SEARCH_RESULT = exports.SET_MOST_RECENT_SEARCH = exports.CLEAR_SEARCH_RESULTS = exports.CLEAR_SELECTED = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _reducers = require('../reducers');

var _cspace = require('./cspace');

var _cspace2 = _interopRequireDefault(_cspace);

var _searchHelpers = require('../helpers/searchHelpers');

var _errorCodes = require('../constants/errorCodes');

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

var CLEAR_SELECTED = exports.CLEAR_SELECTED = 'CLEAR_SELECTED';
var CLEAR_SEARCH_RESULTS = exports.CLEAR_SEARCH_RESULTS = 'CLEAR_SEARCH_RESULTS';
var SET_MOST_RECENT_SEARCH = exports.SET_MOST_RECENT_SEARCH = 'SET_MOST_RECENT_SEARCH';
var CREATE_EMPTY_SEARCH_RESULT = exports.CREATE_EMPTY_SEARCH_RESULT = 'CREATE_EMPTY_SEARCH_RESULT';
var SEARCH_STARTED = exports.SEARCH_STARTED = 'SEARCH_STARTED';
var SEARCH_FULFILLED = exports.SEARCH_FULFILLED = 'SEARCH_FULFILLED';
var SEARCH_REJECTED = exports.SEARCH_REJECTED = 'SEARCH_REJECTED';
var SET_ALL_RESULT_ITEMS_SELECTED = exports.SET_ALL_RESULT_ITEMS_SELECTED = 'SET_ALL_RESULT_ITEMS_SELECTED';
var SET_RESULT_ITEM_SELECTED = exports.SET_RESULT_ITEM_SELECTED = 'SET_RESULT_ITEM_SELECTED';
var DESELECT_RESULT_ITEM = exports.DESELECT_RESULT_ITEM = 'DESELECT_RESULT_ITEM';

var getSortParam = function getSortParam(config, searchDescriptor, columnSetName) {
  var sortSpec = searchDescriptor.getIn(['searchQuery', 'sort']);

  var _sortSpec$split = sortSpec.split(' '),
      _sortSpec$split2 = _slicedToArray(_sortSpec$split, 2),
      sortColumnName = _sortSpec$split2[0],
      sortDir = _sortSpec$split2[1];

  if (sortDir && sortDir !== 'desc') {
    return null;
  }

  var column = (0, _get2.default)(config, ['recordTypes', searchDescriptor.get('recordType'), 'columns', columnSetName, sortColumnName]);

  if (column && column.sortBy) {
    return column.sortBy + (sortDir ? ' DESC' : '');
  }

  return null;
};

var clearSelected = exports.clearSelected = function clearSelected(searchName) {
  return {
    type: CLEAR_SELECTED,
    meta: {
      searchName: searchName
    }
  };
};

var clearSearchResults = exports.clearSearchResults = function clearSearchResults(searchName) {
  return {
    type: CLEAR_SEARCH_RESULTS,
    meta: {
      searchName: searchName
    }
  };
};

var search = exports.search = function search(config, searchName, searchDescriptor) {
  var listType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'common';
  var columnSetName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'default';
  return function (dispatch, getState) {
    var recordType = searchDescriptor.get('recordType');
    var vocabulary = searchDescriptor.get('vocabulary');
    var csid = searchDescriptor.get('csid');
    var subresource = searchDescriptor.get('subresource');
    var searchQuery = searchDescriptor.get('searchQuery');

    if ((0, _reducers.isSearchPending)(getState(), searchName, searchDescriptor) || (0, _reducers.getSearchResult)(getState(), searchName, searchDescriptor)) {
      // There's already a result for this search. Just set this search to be the most recent.

      dispatch({
        type: SET_MOST_RECENT_SEARCH,
        meta: {
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });

      return Promise.resolve();
    }

    var listTypeConfig = config.listTypes[listType];

    dispatch({
      type: SEARCH_STARTED,
      meta: {
        listTypeConfig: listTypeConfig,
        searchName: searchName,
        searchDescriptor: searchDescriptor
      }
    });

    var recordTypeConfig = config.recordTypes[recordType];

    if (!recordTypeConfig) {
      dispatch({
        type: SEARCH_REJECTED,
        payload: {
          code: _errorCodes.ERR_UNKNOWN_RECORD_TYPE
        },
        meta: {
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });

      return Promise.reject();
    }

    var recordTypeServicePath = (0, _get2.default)(recordTypeConfig, ['serviceConfig', 'servicePath']);

    if (!recordTypeServicePath) {
      dispatch({
        type: SEARCH_REJECTED,
        payload: {
          code: _errorCodes.ERR_UNKNOWN_RECORD_TYPE
        },
        meta: {
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });

      return Promise.reject();
    }

    var vocabularyServicePath = vocabulary ? (0, _get2.default)(recordTypeConfig, ['vocabularies', vocabulary, 'serviceConfig', 'servicePath']) : null;

    if (vocabulary && !vocabularyServicePath) {
      dispatch({
        type: SEARCH_REJECTED,
        payload: {
          code: _errorCodes.ERR_UNKNOWN_VOCABULARY
        },
        meta: {
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });

      return Promise.reject();
    }

    // Check for conditions where we just want to create an empty result.
    // These happen when a new record is being created.

    if (
    // A related record search for an empty csid.

    searchQuery.get('rel') === '' ||

    // A subresource query without a csid.

    typeof subresource !== 'undefined' && !searchDescriptor.get('csid')) {
      dispatch({
        type: CREATE_EMPTY_SEARCH_RESULT,
        meta: {
          listTypeConfig: listTypeConfig,
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });

      return Promise.resolve();
    }

    var nxql = (0, _searchHelpers.advancedSearchConditionToNXQL)(recordTypeConfig.fields, searchQuery.get('as'));

    var requestConfig = {
      params: {
        as: nxql ? '(' + nxql + ')' : undefined,
        csid: searchQuery.get('csid'),
        doctype: searchQuery.get('doctype'),
        kw: searchQuery.get('kw'),
        mkRtSbj: searchQuery.get('mkRtSbj'),
        pgNum: searchQuery.get('p'),
        pgSz: searchQuery.get('size'),
        rtSbj: searchQuery.get('rel'),
        rtPredicate: searchQuery.get('relType'),
        sn: searchQuery.get('sn'), // accounts screen name
        wf_deleted: false
      }
    };

    if (searchQuery.get('sort')) {
      var sortParam = getSortParam(config, searchDescriptor, columnSetName);

      if (!sortParam) {
        dispatch({
          type: SEARCH_REJECTED,
          payload: {
            code: _errorCodes.ERR_INVALID_SORT
          },
          meta: {
            searchName: searchName,
            searchDescriptor: searchDescriptor
          }
        });

        return Promise.reject();
      }

      requestConfig.params.sortBy = sortParam;
    }

    var pathParts = [recordTypeServicePath];

    if (vocabularyServicePath) {
      pathParts.push(vocabularyServicePath);
      pathParts.push('items');
    }

    if (csid) {
      pathParts.push(csid);
    }

    if (subresource) {
      var subresourceConfig = config.subresources[subresource];
      var subresourceServicePath = subresourceConfig.serviceConfig.servicePath;

      pathParts.push(subresourceServicePath);
    }

    var path = pathParts.join('/');

    return (0, _cspace2.default)().read(path, requestConfig)
    // Insert an artificial delay for testing.
    // .then(response => new Promise((resolve) => {
    //   window.setTimeout(() => {
    //     resolve(response);
    //   }, 1000);
    // }))
    .then(function (response) {
      return dispatch({
        type: SEARCH_FULFILLED,
        payload: response,
        meta: {
          listTypeConfig: listTypeConfig,
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });
    }).catch(function (error) {
      return dispatch({
        type: SEARCH_REJECTED,
        payload: {
          code: _errorCodes.ERR_API,
          error: error
        },
        meta: {
          searchName: searchName,
          searchDescriptor: searchDescriptor
        }
      });
    });
  };
};

var setResultItemSelected = exports.setResultItemSelected = function setResultItemSelected(config, searchName, searchDescriptor) {
  var listType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'common';
  var index = arguments[4];
  var isSelected = arguments[5];

  var listTypeConfig = config.listTypes[listType];

  return {
    type: SET_RESULT_ITEM_SELECTED,
    payload: isSelected,
    meta: {
      listTypeConfig: listTypeConfig,
      searchName: searchName,
      searchDescriptor: searchDescriptor,
      index: index
    }
  };
};

var setAllResultItemsSelected = exports.setAllResultItemsSelected = function setAllResultItemsSelected(config, searchName, searchDescriptor) {
  var listType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'common';
  var isSelected = arguments[4];
  var filter = arguments[5];

  var listTypeConfig = config.listTypes[listType];

  return {
    type: SET_ALL_RESULT_ITEMS_SELECTED,
    payload: isSelected,
    meta: {
      filter: filter,
      listTypeConfig: listTypeConfig,
      searchName: searchName,
      searchDescriptor: searchDescriptor
    }
  };
};

var deselectResultItem = exports.deselectResultItem = function deselectResultItem(searchName, csid) {
  return {
    type: DESELECT_RESULT_ITEM,
    meta: {
      searchName: searchName,
      csid: csid
    }
  };
};