"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createConnectedSearchSessionIndicator = void 0;
var _react = _interopRequireWildcard(require("react"));
var _operators = require("rxjs/operators");
var _rxjs = require("rxjs");
var _useObservable = _interopRequireDefault(require("react-use/lib/useObservable"));
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/kibana-react-plugin/public");
var _search_session_indicator = require("../search_session_indicator");
var _search_session_tour = require("./search_session_tour");
var _search_session_state = require("../../search_session_state");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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.
 */

const createConnectedSearchSessionIndicator = ({
  sessionService,
  application,
  storage,
  usageCollector,
  basePath,
  tourDisabled
}) => {
  const searchSessionsManagementUrl = basePath.prepend('/app/management/kibana/search_sessions');
  const debouncedSessionServiceState$ = sessionService.state$.pipe((0, _operators.debounce)(_state => (0, _rxjs.timer)(_state === _search_session_state.SearchSessionState.None ? 50 : 300)) // switch to None faster to quickly remove indicator when navigating away
  );

  return () => {
    const state = (0, _useObservable.default)(debouncedSessionServiceState$, _search_session_state.SearchSessionState.None);
    const isSaveDisabledByApp = sessionService.getSearchSessionIndicatorUiConfig().isDisabled();
    const disableSaveAfterSearchesExpire = (0, _useObservable.default)(sessionService.disableSaveAfterSearchesExpire$, false);
    const [searchSessionIndicator, setSearchSessionIndicator] = (0, _react.useState)(null);
    const searchSessionIndicatorRef = (0, _react.useCallback)(ref => {
      if (ref !== null) {
        setSearchSessionIndicator(ref);
      }
    }, []);
    let saveDisabled = false;
    let saveDisabledReasonText = '';
    let managementDisabled = false;
    let managementDisabledReasonText = '';
    if (disableSaveAfterSearchesExpire) {
      saveDisabled = true;
      saveDisabledReasonText = _i18n.i18n.translate('data.searchSessionIndicator.disabledDueToTimeoutMessage', {
        defaultMessage: 'Search session results expired.'
      });
    }
    if (isSaveDisabledByApp.disabled) {
      saveDisabled = true;
      saveDisabledReasonText = isSaveDisabledByApp.reasonText;
    }

    // check if user doesn't have access to search_sessions and search_sessions mgtm
    // this happens in case there is no app that allows current user to use search session
    if (!sessionService.hasAccess()) {
      managementDisabled = saveDisabled = true;
      managementDisabledReasonText = saveDisabledReasonText = _i18n.i18n.translate('data.searchSessionIndicator.disabledDueToDisabledGloballyMessage', {
        defaultMessage: "You don't have permissions to manage search sessions"
      });
    }
    const {
      markOpenedDone,
      markRestoredDone
    } = (0, _search_session_tour.useSearchSessionTour)(storage, searchSessionIndicator, state, saveDisabled, tourDisabled, usageCollector);
    const onOpened = (0, _react.useCallback)(openedState => {
      markOpenedDone();
      if (openedState === _search_session_state.SearchSessionState.Restored) {
        markRestoredDone();
      }
    }, [markOpenedDone, markRestoredDone]);
    const onContinueInBackground = (0, _react.useCallback)(() => {
      if (saveDisabled) return;
      usageCollector === null || usageCollector === void 0 ? void 0 : usageCollector.trackSessionSentToBackground();
      sessionService.save();
    }, [saveDisabled]);
    const onSaveResults = (0, _react.useCallback)(() => {
      if (saveDisabled) return;
      usageCollector === null || usageCollector === void 0 ? void 0 : usageCollector.trackSessionSavedResults();
      sessionService.save();
    }, [saveDisabled]);
    const onCancel = (0, _react.useCallback)(() => {
      usageCollector === null || usageCollector === void 0 ? void 0 : usageCollector.trackSessionCancelled();
      sessionService.cancel();
    }, []);
    const onViewSearchSessions = (0, _react.useCallback)(() => {
      usageCollector === null || usageCollector === void 0 ? void 0 : usageCollector.trackViewSessionsList();
    }, []);
    (0, _react.useEffect)(() => {
      if (state === _search_session_state.SearchSessionState.Restored) {
        usageCollector === null || usageCollector === void 0 ? void 0 : usageCollector.trackSessionIsRestored();
      }
    }, [state]);
    const {
      name: searchSessionName,
      startTime,
      completedTime,
      canceledTime
    } = (0, _useObservable.default)(sessionService.sessionMeta$, {
      state,
      isContinued: false
    });
    const saveSearchSessionNameFn = (0, _react.useCallback)(async newName => {
      await sessionService.renameCurrentSession(newName);
    }, []);
    if (!sessionService.isSessionStorageReady()) return null;
    return /*#__PURE__*/_react.default.createElement(_public.RedirectAppLinks, {
      application: application
    }, /*#__PURE__*/_react.default.createElement(_search_session_indicator.SearchSessionIndicator, {
      ref: searchSessionIndicatorRef,
      state: state,
      saveDisabled: saveDisabled,
      saveDisabledReasonText: saveDisabledReasonText,
      managementDisabled: managementDisabled,
      managementDisabledReasonText: managementDisabledReasonText,
      onContinueInBackground: onContinueInBackground,
      onSaveResults: onSaveResults,
      onCancel: onCancel,
      onOpened: onOpened,
      onViewSearchSessions: onViewSearchSessions,
      viewSearchSessionsLink: searchSessionsManagementUrl,
      searchSessionName: searchSessionName,
      saveSearchSessionNameFn: saveSearchSessionNameFn,
      startedTime: startTime,
      completedTime: completedTime,
      canceledTime: canceledTime
    }));
  };
};
exports.createConnectedSearchSessionIndicator = createConnectedSearchSessionIndicator;