"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.QueryStringManager = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _lodash = require("lodash");
var _common = require("../../../common");
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

class QueryStringManager {
  constructor(storage, uiSettings) {
    (0, _defineProperty2.default)(this, "query$", void 0);
    (0, _defineProperty2.default)(this, "getUpdates$", () => {
      return this.query$.asObservable().pipe((0, _operators.skip)(1));
    });
    (0, _defineProperty2.default)(this, "getQuery", () => {
      return this.query$.getValue();
    });
    /**
     * Updates the query.
     * @param {Query | AggregateQuery} query
     */
    (0, _defineProperty2.default)(this, "setQuery", query => {
      const curQuery = this.query$.getValue();
      if (!(0, _lodash.isEqual)(query, curQuery)) {
        this.query$.next(query);
      }
    });
    /**
     * Resets the query to the default one.
     */
    (0, _defineProperty2.default)(this, "clearQuery", () => {
      this.setQuery(this.getDefaultQuery());
    });
    this.storage = storage;
    this.uiSettings = uiSettings;
    this.query$ = new _rxjs.BehaviorSubject(this.getDefaultQuery());
  }
  getDefaultLanguage() {
    return this.storage.get(_common.KIBANA_USER_QUERY_LANGUAGE_KEY) || this.uiSettings.get(_common.UI_SETTINGS.SEARCH_QUERY_LANGUAGE);
  }
  getDefaultQuery() {
    return {
      query: '',
      language: this.getDefaultLanguage()
    };
  }
  formatQuery(query) {
    if (!query) {
      return this.getDefaultQuery();
    } else if (typeof query === 'string') {
      return {
        query,
        language: this.getDefaultLanguage()
      };
    } else {
      return query;
    }
  }
}
exports.QueryStringManager = QueryStringManager;