'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 }; }

var SET_SEARCH_PAGE_KEYWORD = exports.SET_SEARCH_PAGE_KEYWORD = 'SET_SEARCH_PAGE_KEYWORD';
var SET_SEARCH_PAGE_ADVANCED = exports.SET_SEARCH_PAGE_ADVANCED = 'SET_SEARCH_PAGE_ADVANCED';

var setSearchPageKeyword = exports.setSearchPageKeyword = function setSearchPageKeyword(value) {
  return {
    type: SET_SEARCH_PAGE_KEYWORD,
    payload: value
  };
};

var setSearchPageAdvanced = exports.setSearchPageAdvanced = function setSearchPageAdvanced(condition) {
  return {
    type: SET_SEARCH_PAGE_ADVANCED,
    payload: condition
  };
};

var initiateSearch = exports.initiateSearch = function initiateSearch(config, push) {
  return function (dispatch, getState) {
    var state = getState();

    var recordType = (0, _reducers.getSearchPageRecordType)(state);
    var vocabulary = (0, _reducers.getSearchPageVocabulary)(state, recordType);
    var keyword = (0, _reducers.getSearchPageKeyword)(state);
    var advancedSearchCondition = (0, _reducers.getSearchPageAdvanced)(state);

    var query = {};
    var vocabularyPath = vocabulary ? '/' + vocabulary : '';
    var pathname = '/list/' + recordType + vocabularyPath;

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

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

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

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

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

    push({
      pathname: pathname,
      search: '?' + queryString
    });
  };
};