'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.initiateSearch = exports.setSearchPageAdvanced = exports.setSearchPageKeyword = exports.SET_SEARCH_PAGE_ADVANCED = exports.SET_SEARCH_PAGE_KEYWORD = undefined;

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

var _get2 = _interopRequireDefault(_get);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

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

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

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

const SET_SEARCH_PAGE_KEYWORD = exports.SET_SEARCH_PAGE_KEYWORD = 'SET_SEARCH_PAGE_KEYWORD';
const SET_SEARCH_PAGE_ADVANCED = exports.SET_SEARCH_PAGE_ADVANCED = 'SET_SEARCH_PAGE_ADVANCED';

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

const setSearchPageAdvanced = exports.setSearchPageAdvanced = condition => ({
  type: SET_SEARCH_PAGE_ADVANCED,
  payload: condition
});

const initiateSearch = exports.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 ? `/${vocabulary}` : '';
  const pathname = `/list/${recordType}${vocabularyPath}`;

  const kw = keyword ? keyword.trim() : '';

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

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

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

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

  push({
    pathname,
    search: `?${queryString}`
  });
};