"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useUrlQuery = void 0;
var _react = require("react");
var _reactRouterDom = require("react-router-dom");
var _query_utils = require("../navigation/query_utils");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

/**
 * @description uses 'rison' to encode/decode a url query
 * @todo replace getDefaultQuery with schema. validate after decoded from URL, use defaultValues
 * @note shallow-merges default, current and next query
 */
const useUrlQuery = getDefaultQuery => {
  const {
    push,
    replace
  } = (0, _reactRouterDom.useHistory)();
  const {
    search,
    key
  } = (0, _reactRouterDom.useLocation)();
  const urlQuery = (0, _react.useMemo)(() => ({
    ...getDefaultQuery(),
    ...(0, _query_utils.decodeQuery)(search)
  }), [getDefaultQuery, search]);
  const setUrlQuery = (0, _react.useCallback)(query => push({
    search: (0, _query_utils.encodeQuery)({
      ...getDefaultQuery(),
      ...urlQuery,
      ...query
    })
  }), [getDefaultQuery, urlQuery, push]);

  // Set initial query
  (0, _react.useEffect)(() => {
    if (search) return;
    replace({
      search: (0, _query_utils.encodeQuery)(getDefaultQuery())
    });
  }, [getDefaultQuery, search, replace]);
  return {
    key,
    urlQuery,
    setUrlQuery
  };
};
exports.useUrlQuery = useUrlQuery;