"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DiscoverMainRoute = DiscoverMainRoute;
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactRouterDom = require("react-router-dom");
var _public = require("@kbn/kibana-utils-plugin/public");
var _public2 = require("@kbn/kibana-react-plugin/public");
var _sharedUxPageAnalyticsNoData = require("@kbn/shared-ux-page-analytics-no-data");
var _public3 = require("@kbn/saved-search-plugin/public");
var _useObservable = _interopRequireDefault(require("react-use/lib/useObservable"));
var _ebtTools = require("@kbn/ebt-tools");
var _use_url = require("./hooks/use_url");
var _use_singleton = require("./hooks/use_singleton");
var _discover_state = require("./services/discover_state");
var _discover_main_app = require("./discover_main_app");
var _breadcrumbs = require("../../utils/breadcrumbs");
var _loading_indicator = require("../../components/common/loading_indicator");
var _error_alert = require("../../components/common/error_alert");
var _use_discover_services = require("../../hooks/use_discover_services");
var _kibana_services = require("../../kibana_services");
var _use_alert_results_toast = require("./hooks/use_alert_results_toast");
var _discover_state_provider = require("./services/discover_state_provider");
var _customizations = require("../../customizations");
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 DiscoverMainAppMemoized = /*#__PURE__*/(0, _react.memo)(_discover_main_app.DiscoverMainApp);
function DiscoverMainRoute({
  customizationCallbacks,
  mode = 'standalone'
}) {
  const history = (0, _reactRouterDom.useHistory)();
  const services = (0, _use_discover_services.useDiscoverServices)();
  const {
    core,
    chrome,
    data,
    toastNotifications,
    http: {
      basePath
    },
    dataViewEditor
  } = services;
  const {
    id: savedSearchId
  } = (0, _reactRouterDom.useParams)();
  const stateContainer = (0, _use_singleton.useSingleton)(() => (0, _discover_state.getDiscoverStateContainer)({
    history,
    services,
    mode
  }));
  const {
    customizationService,
    isInitialized: isCustomizationServiceInitialized
  } = (0, _customizations.useDiscoverCustomizationService)({
    customizationCallbacks,
    stateContainer
  });
  const [error, setError] = (0, _react.useState)();
  const [loading, setLoading] = (0, _react.useState)(true);
  const [hasESData, setHasESData] = (0, _react.useState)(false);
  const [hasUserDataView, setHasUserDataView] = (0, _react.useState)(false);
  const [showNoDataPage, setShowNoDataPage] = (0, _react.useState)(false);
  const hasCustomBranding = (0, _useObservable.default)(core.customBranding.hasCustomBranding$, false);

  /**
   * Get location state of scoped history only on initial load
   */
  const historyLocationState = (0, _react.useMemo)(() => (0, _kibana_services.getScopedHistory)().location.state, []);
  (0, _use_alert_results_toast.useAlertResultsToast)({
    isAlertResults: historyLocationState === null || historyLocationState === void 0 ? void 0 : historyLocationState.isAlertResults,
    toastNotifications
  });
  (0, _public2.useExecutionContext)(core.executionContext, {
    type: 'application',
    page: 'app',
    id: savedSearchId || 'new'
  });
  const checkData = (0, _react.useCallback)(async () => {
    try {
      if (savedSearchId) {
        return true; // bypass NoData screen
      }

      const hasUserDataViewValue = await data.dataViews.hasData.hasUserDataView().catch(() => false);
      const hasESDataValue = await data.dataViews.hasData.hasESData().catch(() => false);
      setHasUserDataView(hasUserDataViewValue);
      setHasESData(hasESDataValue);
      if (!hasUserDataViewValue) {
        setShowNoDataPage(true);
        return false;
      }
      let defaultDataView = null;
      try {
        defaultDataView = await data.dataViews.getDefaultDataView({
          displayErrors: false
        });
      } catch (e) {
        //
      }
      if (!defaultDataView) {
        setShowNoDataPage(true);
        return false;
      }
      return true;
    } catch (e) {
      setError(e);
      return false;
    }
  }, [data.dataViews, savedSearchId]);
  const loadSavedSearch = (0, _react.useCallback)(async nextDataView => {
    const loadSavedSearchStartTime = window.performance.now();
    setLoading(true);
    if (!nextDataView && !(await checkData())) {
      setLoading(false);
      return;
    }
    try {
      await stateContainer.actions.loadDataViewList();
      const currentSavedSearch = await stateContainer.actions.loadSavedSearch({
        savedSearchId,
        dataView: nextDataView,
        dataViewSpec: historyLocationState === null || historyLocationState === void 0 ? void 0 : historyLocationState.dataViewSpec
      });
      if (mode === 'standalone') {
        var _currentSavedSearch$t2;
        if (currentSavedSearch !== null && currentSavedSearch !== void 0 && currentSavedSearch.id) {
          var _currentSavedSearch$t;
          chrome.recentlyAccessed.add((0, _public3.getSavedSearchFullPathUrl)(currentSavedSearch.id), (_currentSavedSearch$t = currentSavedSearch.title) !== null && _currentSavedSearch$t !== void 0 ? _currentSavedSearch$t : '', currentSavedSearch.id);
        }
        (0, _breadcrumbs.setBreadcrumbs)({
          services,
          titleBreadcrumbText: (_currentSavedSearch$t2 = currentSavedSearch === null || currentSavedSearch === void 0 ? void 0 : currentSavedSearch.title) !== null && _currentSavedSearch$t2 !== void 0 ? _currentSavedSearch$t2 : undefined
        });
      }
      setLoading(false);
      if (services.analytics) {
        const loadSavedSearchDuration = window.performance.now() - loadSavedSearchStartTime;
        (0, _ebtTools.reportPerformanceMetricEvent)(services.analytics, {
          eventName: 'discoverLoadSavedSearch',
          duration: loadSavedSearchDuration
        });
      }
    } catch (e) {
      if (e instanceof _public.SavedObjectNotFound) {
        (0, _public.redirectWhenMissing)({
          history,
          navigateToApp: core.application.navigateToApp,
          basePath,
          mapping: {
            search: '/',
            'index-pattern': {
              app: 'management',
              path: `kibana/objects/savedSearches/${savedSearchId}`
            }
          },
          toastNotifications,
          onBeforeRedirect() {
            (0, _kibana_services.getUrlTracker)().setTrackedUrl('/');
          },
          theme: core.theme
        })(e);
      } else {
        setError(e);
      }
    }
  }, [checkData, stateContainer, savedSearchId, historyLocationState === null || historyLocationState === void 0 ? void 0 : historyLocationState.dataViewSpec, chrome, services, history, core.application.navigateToApp, core.theme, basePath, toastNotifications, mode]);
  const onDataViewCreated = (0, _react.useCallback)(async nextDataView => {
    if (nextDataView) {
      setLoading(true);
      setShowNoDataPage(false);
      setError(undefined);
      await loadSavedSearch(nextDataView);
    }
  }, [loadSavedSearch]);
  (0, _react.useEffect)(() => {
    if (!isCustomizationServiceInitialized) return;
    setLoading(true);
    setHasESData(false);
    setHasUserDataView(false);
    setShowNoDataPage(false);
    setError(undefined);
    // restore the previously selected data view for a new state
    loadSavedSearch(!savedSearchId ? stateContainer.internalState.getState().dataView : undefined);
  }, [isCustomizationServiceInitialized, loadSavedSearch, savedSearchId, stateContainer]);

  // secondary fetch: in case URL is set to `/`, used to reset to 'new' state, keeping the current data view
  (0, _use_url.useUrl)({
    history,
    savedSearchId,
    onNewUrl: () => {
      // restore the previously selected data view for a new state
      const dataView = stateContainer.internalState.getState().dataView;
      loadSavedSearch(dataView);
    }
  });
  if (showNoDataPage) {
    const analyticsServices = {
      coreStart: core,
      dataViews: {
        ...data.dataViews,
        hasData: {
          ...data.dataViews.hasData,
          // We've already called this, so we can optimize the analytics services to
          // use the already-retrieved data to avoid a double-call.
          hasESData: () => Promise.resolve(hasESData),
          hasUserDataView: () => Promise.resolve(hasUserDataView)
        }
      },
      dataViewEditor,
      noDataPage: services.noDataPage
    };
    return /*#__PURE__*/_react.default.createElement(_sharedUxPageAnalyticsNoData.AnalyticsNoDataPageKibanaProvider, analyticsServices, /*#__PURE__*/_react.default.createElement(_sharedUxPageAnalyticsNoData.AnalyticsNoDataPage, {
      onDataViewCreated: onDataViewCreated
    }));
  }
  if (error) {
    return /*#__PURE__*/_react.default.createElement(_error_alert.DiscoverError, {
      error: error
    });
  }
  if (loading || !customizationService) {
    return /*#__PURE__*/_react.default.createElement(_loading_indicator.LoadingIndicator, {
      type: hasCustomBranding ? 'spinner' : 'elastic'
    });
  }
  return /*#__PURE__*/_react.default.createElement(_customizations.DiscoverCustomizationProvider, {
    value: customizationService
  }, /*#__PURE__*/_react.default.createElement(_discover_state_provider.DiscoverMainProvider, {
    value: stateContainer
  }, /*#__PURE__*/_react.default.createElement(DiscoverMainAppMemoized, {
    stateContainer: stateContainer,
    mode: mode
  })));
}
// eslint-disable-next-line import/no-default-export
var _default = DiscoverMainRoute;
exports.default = _default;