'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.initiateSearch = exports.setQuickSearchKeyword = exports.SET_QUICK_SEARCH_KEYWORD = undefined;

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _csidHelpers = require('../helpers/csidHelpers');

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

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

const SET_QUICK_SEARCH_KEYWORD = exports.SET_QUICK_SEARCH_KEYWORD = 'SET_QUICK_SEARCH_KEYWORD';

const setQuickSearchKeyword = exports.setQuickSearchKeyword = value => ({
  type: SET_QUICK_SEARCH_KEYWORD,
  payload: value
});

const initiateSearch = exports.initiateSearch = push => (dispatch, getState) => {
  const keyword = (0, _reducers.getQuickSearchKeyword)(getState());
  const kw = keyword ? keyword.trim() : '';
  const recordType = (0, _reducers.getQuickSearchRecordType)(getState());
  const vocabulary = (0, _reducers.getQuickSearchVocabulary)(getState(), recordType);

  let pathname;
  let search;

  const vocabularyPath = vocabulary ? `/${vocabulary}` : '';

  if ((0, _csidHelpers.isCsid)(kw)) {
    // Go straight to the record with the csid.

    pathname = `/record/${recordType}${vocabularyPath}/${kw}`;
  } else {
    pathname = `/list/${recordType}${vocabularyPath}`;

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

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

      search = `?${queryString}`;
    }
  }

  push({
    pathname,
    search
  });
};