"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DiscoverTopNav = void 0;
var _react = _interopRequireWildcard(require("react"));
var _public = require("@kbn/data-views-plugin/public");
var _discoverUtils = require("@kbn/discover-utils");
var _discover_state_provider = require("../../services/discover_state_provider");
var _discover_internal_state_container = require("../../services/discover_internal_state_container");
var _use_discover_services = require("../../../../hooks/use_discover_services");
var _get_top_nav_links = require("./get_top_nav_links");
var _kibana_services = require("../../../../kibana_services");
var _on_save_search = require("./on_save_search");
var _customizations = require("../../../../customizations");
var _add_log = require("../../../../utils/add_log");
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 DiscoverTopNav = ({
  onOpenInspector,
  query,
  savedQuery,
  stateContainer,
  updateQuery,
  isPlainRecord,
  textBasedLanguageModeErrors,
  textBasedLanguageModeWarning,
  onFieldEdited
}) => {
  const adHocDataViews = (0, _discover_internal_state_container.useInternalStateSelector)(state => state.adHocDataViews);
  const dataView = (0, _discover_internal_state_container.useInternalStateSelector)(state => state.dataView);
  const savedDataViews = (0, _discover_internal_state_container.useInternalStateSelector)(state => state.savedDataViews);
  const savedSearch = (0, _discover_state_provider.useSavedSearchInitial)();
  const showDatePicker = (0, _react.useMemo)(() => {
    // always show the timepicker for text based languages
    return isPlainRecord || !isPlainRecord && dataView.isTimeBased() && dataView.type !== _public.DataViewType.ROLLUP;
  }, [dataView, isPlainRecord]);
  const services = (0, _use_discover_services.useDiscoverServices)();
  const {
    dataViewEditor,
    navigation,
    dataViewFieldEditor,
    data,
    uiSettings,
    dataViews
  } = services;
  const canEditDataView = Boolean(dataViewEditor === null || dataViewEditor === void 0 ? void 0 : dataViewEditor.userPermissions.editDataView()) || !dataView.isPersisted();
  const closeFieldEditor = (0, _react.useRef)();
  const closeDataViewEditor = (0, _react.useRef)();
  const {
    AggregateQueryTopNavMenu
  } = navigation.ui;
  (0, _react.useEffect)(() => {
    return () => {
      // Make sure to close the editors when unmounting
      if (closeFieldEditor.current) {
        closeFieldEditor.current();
      }
      if (closeDataViewEditor.current) {
        closeDataViewEditor.current();
      }
    };
  }, []);
  const editField = (0, _react.useMemo)(() => canEditDataView ? async (fieldName, uiAction = 'edit') => {
    if (dataView !== null && dataView !== void 0 && dataView.id) {
      const dataViewInstance = await data.dataViews.get(dataView.id);
      closeFieldEditor.current = dataViewFieldEditor.openEditor({
        ctx: {
          dataView: dataViewInstance
        },
        fieldName,
        onSave: async () => {
          await onFieldEdited();
        }
      });
    }
  } : undefined, [canEditDataView, dataView === null || dataView === void 0 ? void 0 : dataView.id, data.dataViews, dataViewFieldEditor, onFieldEdited]);
  const addField = (0, _react.useMemo)(() => canEditDataView && editField ? () => editField(undefined, 'add') : undefined, [editField, canEditDataView]);
  const createNewDataView = (0, _react.useCallback)(() => {
    closeDataViewEditor.current = dataViewEditor.openEditor({
      onSave: stateContainer.actions.onDataViewCreated,
      allowAdHocDataView: true
    });
  }, [dataViewEditor, stateContainer]);
  const topNavCustomization = (0, _customizations.useDiscoverCustomization)('top_nav');
  const topNavMenu = (0, _react.useMemo)(() => (0, _get_top_nav_links.getTopNavLinks)({
    dataView,
    services,
    state: stateContainer,
    onOpenInspector,
    isPlainRecord,
    adHocDataViews,
    topNavCustomization
  }), [adHocDataViews, dataView, isPlainRecord, onOpenInspector, services, stateContainer, topNavCustomization]);
  const onEditDataView = async editedDataView => {
    if (editedDataView.isPersisted()) {
      // Clear the current data view from the cache and create a new instance
      // of it, ensuring we have a new object reference to trigger a re-render
      dataViews.clearInstanceCache(editedDataView.id);
      stateContainer.actions.setDataView(await dataViews.create(editedDataView.toSpec(), true));
    } else {
      await stateContainer.actions.updateAdHocDataViewId();
    }
    stateContainer.actions.loadDataViewList();
    (0, _add_log.addLog)('[DiscoverTopNav] onEditDataView triggers data fetching');
    stateContainer.dataState.fetch();
  };
  const updateSavedQueryId = newSavedQueryId => {
    const {
      appState
    } = stateContainer;
    if (newSavedQueryId) {
      appState.update({
        savedQuery: newSavedQueryId
      });
    } else {
      // remove savedQueryId from state
      const newState = {
        ...appState.getState()
      };
      delete newState.savedQuery;
      appState.set(newState);
    }
  };
  const setMenuMountPoint = (0, _react.useMemo)(() => {
    return (0, _kibana_services.getHeaderActionMenuMounter)();
  }, []);
  const isESQLModeEnabled = uiSettings.get(_discoverUtils.ENABLE_ESQL);
  const supportedTextBasedLanguages = [];
  if (isESQLModeEnabled) {
    supportedTextBasedLanguages.push('ESQL');
  }
  const searchBarCustomization = (0, _customizations.useDiscoverCustomization)('search_bar');
  const SearchBar = (0, _react.useMemo)(() => {
    var _searchBarCustomizati;
    return (_searchBarCustomizati = searchBarCustomization === null || searchBarCustomization === void 0 ? void 0 : searchBarCustomization.CustomSearchBar) !== null && _searchBarCustomizati !== void 0 ? _searchBarCustomizati : AggregateQueryTopNavMenu;
  }, [searchBarCustomization === null || searchBarCustomization === void 0 ? void 0 : searchBarCustomization.CustomSearchBar, AggregateQueryTopNavMenu]);
  const shouldHideDefaultDataviewPicker = !!(searchBarCustomization !== null && searchBarCustomization !== void 0 && searchBarCustomization.CustomDataViewPicker) || !!(searchBarCustomization !== null && searchBarCustomization !== void 0 && searchBarCustomization.hideDataViewPicker);
  const dataViewPickerProps = {
    trigger: {
      label: (dataView === null || dataView === void 0 ? void 0 : dataView.getName()) || '',
      'data-test-subj': 'discover-dataView-switch-link',
      title: (dataView === null || dataView === void 0 ? void 0 : dataView.getIndexPattern()) || ''
    },
    currentDataViewId: dataView === null || dataView === void 0 ? void 0 : dataView.id,
    onAddField: addField,
    onDataViewCreated: createNewDataView,
    onCreateDefaultAdHocDataView: stateContainer.actions.createAndAppendAdHocDataView,
    onChangeDataView: stateContainer.actions.onChangeDataView,
    textBasedLanguages: supportedTextBasedLanguages,
    adHocDataViews,
    savedDataViews,
    onEditDataView
  };
  const onTextBasedSavedAndExit = (0, _react.useCallback)(({
    onSave,
    onCancel
  }) => {
    (0, _on_save_search.onSaveSearch)({
      savedSearch: stateContainer.savedSearchState.getState(),
      services,
      state: stateContainer,
      onClose: onCancel,
      onSaveCb: onSave
    });
  }, [services, stateContainer]);
  return /*#__PURE__*/_react.default.createElement(SearchBar, {
    appName: "discover",
    config: topNavMenu,
    indexPatterns: [dataView],
    onQuerySubmit: updateQuery,
    onSavedQueryIdChange: updateSavedQueryId,
    query: query,
    setMenuMountPoint: setMenuMountPoint,
    savedQueryId: savedQuery,
    screenTitle: savedSearch.title,
    showDatePicker: showDatePicker,
    saveQueryMenuVisibility: services.capabilities.discover.saveQuery ? 'allowed_by_app_privilege' : 'globally_managed',
    showSearchBar: true,
    useDefaultBehaviors: true,
    dataViewPickerOverride: searchBarCustomization !== null && searchBarCustomization !== void 0 && searchBarCustomization.CustomDataViewPicker ? /*#__PURE__*/_react.default.createElement(searchBarCustomization.CustomDataViewPicker, null) : undefined,
    dataViewPickerComponentProps: shouldHideDefaultDataviewPicker ? undefined : dataViewPickerProps,
    displayStyle: "detached",
    textBasedLanguageModeErrors: textBasedLanguageModeErrors ? [textBasedLanguageModeErrors] : undefined,
    textBasedLanguageModeWarning: textBasedLanguageModeWarning,
    onTextBasedSavedAndExit: onTextBasedSavedAndExit,
    prependFilterBar: searchBarCustomization !== null && searchBarCustomization !== void 0 && searchBarCustomization.PrependFilterBar ? /*#__PURE__*/_react.default.createElement(searchBarCustomization.PrependFilterBar, null) : undefined
  });
};
exports.DiscoverTopNav = DiscoverTopNav;