"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AlertsPopover = AlertsPopover;
exports.openAlertsPopover = openAlertsPopover;
var _react = _interopRequireWildcard(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _reactKibanaContextRender = require("@kbn/react-kibana-context-render");
var _public = require("@kbn/kibana-react-plugin/public");
var _ruleDataUtils = require("@kbn/rule-data-utils");
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 container = document.createElement('div');
let isOpen = false;
const ALERT_TYPE_ID = '.es-query';
function AlertsPopover({
  anchorElement,
  adHocDataViews,
  services,
  stateContainer,
  onClose: originalOnClose,
  isPlainRecord
}) {
  var _dateFields$, _services$application;
  const dataView = stateContainer.internalState.getState().dataView;
  const query = stateContainer.appState.getState().query;
  const dateFields = dataView === null || dataView === void 0 ? void 0 : dataView.fields.getByType('date');
  const timeField = (dataView === null || dataView === void 0 ? void 0 : dataView.timeFieldName) || (dateFields === null || dateFields === void 0 ? void 0 : (_dateFields$ = dateFields[0]) === null || _dateFields$ === void 0 ? void 0 : _dateFields$.name);
  const {
    triggersActionsUi
  } = services;
  const [alertFlyoutVisible, setAlertFlyoutVisibility] = (0, _react.useState)(false);
  const onClose = (0, _react.useCallback)(() => {
    originalOnClose();
    anchorElement === null || anchorElement === void 0 ? void 0 : anchorElement.focus();
  }, [anchorElement, originalOnClose]);

  /**
   * Provides the default parameters used to initialize the new rule
   */
  const getParams = (0, _react.useCallback)(() => {
    if (isPlainRecord) {
      return {
        searchType: 'esqlQuery',
        esqlQuery: query,
        timeField
      };
    }
    const savedQueryId = stateContainer.appState.getState().savedQuery;
    return {
      searchType: 'searchSource',
      searchConfiguration: stateContainer.savedSearchState.getState().searchSource.getSerializedFields(),
      savedQueryId
    };
  }, [isPlainRecord, stateContainer.appState, stateContainer.savedSearchState, query, timeField]);
  const discoverMetadata = (0, _react.useMemo)(() => ({
    isManagementPage: false,
    adHocDataViewList: adHocDataViews
  }), [adHocDataViews]);
  const SearchThresholdAlertFlyout = (0, _react.useMemo)(() => {
    if (!alertFlyoutVisible) {
      return;
    }
    const onFinishFlyoutInteraction = async metadata => {
      await stateContainer.actions.loadDataViewList();
      stateContainer.internalState.transitions.setAdHocDataViews(metadata.adHocDataViewList);
    };
    return triggersActionsUi === null || triggersActionsUi === void 0 ? void 0 : triggersActionsUi.getAddRuleFlyout({
      metadata: discoverMetadata,
      consumer: _ruleDataUtils.STACK_ALERTS_FEATURE_ID,
      onClose: (_, metadata) => {
        onFinishFlyoutInteraction(metadata);
        onClose();
      },
      onSave: async metadata => {
        onFinishFlyoutInteraction(metadata);
      },
      canChangeTrigger: false,
      ruleTypeId: ALERT_TYPE_ID,
      initialValues: {
        params: getParams()
      }
    });
  }, [alertFlyoutVisible, triggersActionsUi, discoverMetadata, getParams, onClose, stateContainer]);
  const hasTimeFieldName = (0, _react.useMemo)(() => {
    if (!isPlainRecord) {
      return Boolean(dataView === null || dataView === void 0 ? void 0 : dataView.timeFieldName);
    } else {
      return Boolean(timeField);
    }
  }, [dataView === null || dataView === void 0 ? void 0 : dataView.timeFieldName, isPlainRecord, timeField]);
  const panels = [{
    id: 'mainPanel',
    name: 'Alerting',
    items: [{
      name: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "discover.alerts.createSearchThreshold",
        defaultMessage: "Create search threshold rule"
      }),
      icon: 'bell',
      onClick: () => setAlertFlyoutVisibility(true),
      disabled: !hasTimeFieldName,
      toolTipContent: hasTimeFieldName ? undefined : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "discover.alerts.missedTimeFieldToolTip",
        defaultMessage: "Data view does not have a time field."
      }),
      ['data-test-subj']: 'discoverCreateAlertButton'
    }, {
      name: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "discover.alerts.manageRulesAndConnectors",
        defaultMessage: "Manage rules and connectors"
      }),
      icon: 'tableOfContents',
      href: services === null || services === void 0 ? void 0 : (_services$application = services.application) === null || _services$application === void 0 ? void 0 : _services$application.getUrlForApp('management/insightsAndAlerting/triggersActions/alerts'),
      ['data-test-subj']: 'discoverManageAlertsButton'
    }]
  }];
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, SearchThresholdAlertFlyout, /*#__PURE__*/_react.default.createElement(_eui.EuiWrappingPopover, {
    ownFocus: true,
    button: anchorElement,
    closePopover: onClose,
    isOpen: !alertFlyoutVisible
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiContextMenu, {
    initialPanelId: "mainPanel",
    panels: panels
  })));
}
function closeAlertsPopover() {
  _reactDom.default.unmountComponentAtNode(container);
  document.body.removeChild(container);
  isOpen = false;
}
function openAlertsPopover({
  anchorElement,
  stateContainer,
  services,
  adHocDataViews,
  isPlainRecord
}) {
  if (isOpen) {
    closeAlertsPopover();
    return;
  }
  isOpen = true;
  document.body.appendChild(container);
  const element = /*#__PURE__*/_react.default.createElement(_reactKibanaContextRender.KibanaRenderContextProvider, {
    theme: services.core.theme,
    i18n: services.core.i18n
  }, /*#__PURE__*/_react.default.createElement(_public.KibanaContextProvider, {
    services: services
  }, /*#__PURE__*/_react.default.createElement(AlertsPopover, {
    onClose: closeAlertsPopover,
    anchorElement: anchorElement,
    stateContainer: stateContainer,
    adHocDataViews: adHocDataViews,
    services: services,
    isPlainRecord: isPlainRecord
  })));
  _reactDom.default.render(element, container);
}