"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.initiateSearch = exports.setSearchPageAdvanced = exports.setSearchPageKeyword = exports.clearSearchPage = void 0;

var _get = _interopRequireDefault(require("lodash/get"));

var _qs = _interopRequireDefault(require("qs"));

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

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

var _actionCodes = require("../constants/actionCodes");

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

const clearSearchPage = () => ({
  type: _actionCodes.CLEAR_SEARCH_PAGE
});

exports.clearSearchPage = clearSearchPage;

const setSearchPageKeyword = value => ({
  type: _actionCodes.SET_SEARCH_PAGE_KEYWORD,
  payload: value
});

exports.setSearchPageKeyword = setSearchPageKeyword;

const setSearchPageAdvanced = condition => (dispatch, getState) => {
  const recordType = (0, _reducers.getSearchPageRecordType)(getState());
  dispatch({
    type: _actionCodes.SET_SEARCH_PAGE_ADVANCED,
    payload: condition,
    meta: {
      recordType
    }
  });
};

exports.setSearchPageAdvanced = setSearchPageAdvanced;

const initiateSearch = (config, push) => (dispatch, getState) => {
  const state = getState();
  const recordType = (0, _reducers.getSearchPageRecordType)(state);
  const vocabulary = (0, _reducers.getSearchPageVocabulary)(state, recordType);
  const keyword = (0, _reducers.getSearchPageKeyword)(state);
  const advancedSearchCondition = (0, _reducers.getSearchPageAdvanced)(state);
  const query = {};
  const vocabularyPath = vocabulary ? "/".concat(vocabulary) : '';
  const pathname = "/list/".concat(recordType).concat(vocabularyPath);
  const kw = keyword ? keyword.trim() : '';

  if (kw) {
    query.kw = kw;
  }

  const fields = (0, _get.default)(config, ['recordTypes', recordType, 'fields']);
  const condition = (0, _searchHelpers.normalizeCondition)(fields, advancedSearchCondition);

  if (condition) {
    query.as = JSON.stringify(condition.toJS());
  }

  const queryString = _qs.default.stringify(query);

  push({
    pathname,
    search: "?".concat(queryString),
    state: {
      originSearchPage: {
        // Keep the search descriptor a plain object, not an Immutable, so that it can be stored in
        // location state.
        searchDescriptor: {
          recordType,
          vocabulary,
          searchQuery: {
            as: advancedSearchCondition && advancedSearchCondition.toJS(),
            kw: keyword
          }
        }
      }
    }
  });
};

exports.initiateSearch = initiateSearch;