"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ResultsLinks = void 0;
var _react = _interopRequireWildcard(require("react"));
var _moment = _interopRequireDefault(require("moment"));
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _lodash = require("lodash");
var _mlIsDefined = require("@kbn/ml-is-defined");
var _kibana_context = require("../../../kibana_context");
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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const RECHECK_DELAY_MS = 3000;
const ResultsLinks = ({
  fieldStats,
  index,
  dataViewId,
  timeFieldName,
  createDataView,
  showFilebeatFlyout,
  getAdditionalLinks
}) => {
  const {
    services: {
      fileUpload,
      application: {
        getUrlForApp,
        capabilities
      },
      discover
    }
  } = (0, _kibana_context.useDataVisualizerKibana)();
  const [duration, setDuration] = (0, _react.useState)({
    from: 'now-30m',
    to: 'now'
  });
  const [globalState, setGlobalState] = (0, _react.useState)();
  const [discoverLink, setDiscoverLink] = (0, _react.useState)('');
  const [indexManagementLink, setIndexManagementLink] = (0, _react.useState)('');
  const [dataViewsManagementLink, setDataViewsManagementLink] = (0, _react.useState)('');
  const [asyncHrefCards, setAsyncHrefCards] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    let unmounted = false;
    const getDiscoverUrl = async () => {
      var _capabilities$discove, _capabilities$discove2;
      const isDiscoverAvailable = (_capabilities$discove = (_capabilities$discove2 = capabilities.discover) === null || _capabilities$discove2 === void 0 ? void 0 : _capabilities$discove2.show) !== null && _capabilities$discove !== void 0 ? _capabilities$discove : false;
      if (!isDiscoverAvailable) return;
      if (!discover.locator) {
        // eslint-disable-next-line no-console
        console.error('Discover locator not available');
        return;
      }
      const discoverUrl = await discover.locator.getUrl({
        indexPatternId: dataViewId,
        timeRange: globalState !== null && globalState !== void 0 && globalState.time ? globalState.time : undefined
      });
      if (unmounted) return;
      setDiscoverLink(discoverUrl);
    };
    getDiscoverUrl();
    if (Array.isArray(getAdditionalLinks)) {
      Promise.all(getAdditionalLinks.map(async asyncCardGetter => {
        const results = await asyncCardGetter({
          dataViewId,
          globalState
        });
        if (Array.isArray(results)) {
          return await Promise.all(results.map(async c => ({
            ...c,
            canDisplay: await c.canDisplay(),
            href: await c.getUrl()
          })));
        }
      })).then(cards => {
        setAsyncHrefCards((0, _lodash.flatten)(cards).filter(_mlIsDefined.isDefined).filter(d => d.canDisplay === true));
      });
    }
    if (!unmounted) {
      setIndexManagementLink(getUrlForApp('management', {
        path: '/data/index_management/indices'
      }));
      if (capabilities.indexPatterns.save === true) {
        setDataViewsManagementLink(getUrlForApp('management', {
          path: `/kibana/dataViews${createDataView ? `/dataView/${dataViewId}` : ''}`
        }));
      }
    }
    return () => {
      unmounted = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataViewId, discover, JSON.stringify(globalState)]);
  (0, _react.useEffect)(() => {
    updateTimeValues();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    const _globalState = {
      time: {
        from: duration.from,
        to: duration.to
      }
    };
    setGlobalState(_globalState);
  }, [duration]);
  (0, _react.useEffect)(() => {
    // Update the global time range from known timeFieldName if stats is available
    if (fieldStats && typeof fieldStats === 'object' && timeFieldName !== undefined && fieldStats.hasOwnProperty(timeFieldName) && fieldStats[timeFieldName].earliest !== undefined && fieldStats[timeFieldName].latest !== undefined) {
      setGlobalState({
        time: {
          from: fieldStats[timeFieldName].earliest,
          to: fieldStats[timeFieldName].latest
        }
      });
    }
  }, [timeFieldName, fieldStats]);
  async function updateTimeValues(recheck = true) {
    if (timeFieldName !== undefined) {
      const {
        from,
        to
      } = await getFullTimeRange(index, timeFieldName, fileUpload);
      setDuration({
        from: from === null ? duration.from : from,
        to: to === null ? duration.to : to
      });

      // these links may have been drawn too quickly for the index to be ready
      // to give us the correct start and end times.
      // especially if the data was small.
      // so if the start and end were null, try again in 3s
      if (recheck && (from === null || to === null)) {
        setTimeout(() => {
          updateTimeValues(false);
        }, RECHECK_DELAY_MS);
      }
    }
  }
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "l"
  }, createDataView && discoverLink && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "xxl",
      type: `discoverApp`
    }),
    title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.file.resultsLinks.viewIndexInDiscoverTitle",
      defaultMessage: "View index in Discover"
    }),
    description: "",
    href: discoverLink
  })), indexManagementLink && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "xxl",
      type: `managementApp`
    }),
    title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.file.resultsLinks.indexManagementTitle",
      defaultMessage: "Index Management"
    }),
    description: "",
    href: indexManagementLink
  })), dataViewsManagementLink && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "xxl",
      type: `managementApp`
    }),
    title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.file.resultsLinks.dataViewManagementTitle",
      defaultMessage: "Data View Management"
    }),
    description: "",
    href: dataViewsManagementLink
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "xxl",
      type: `filebeatApp`
    }),
    "data-test-subj": "fileDataVisFilebeatConfigLink",
    title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.dataVisualizer.file.resultsLinks.fileBeatConfig",
      defaultMessage: "Create Filebeat configuration"
    }),
    description: "",
    onClick: showFilebeatFlyout
  })), Array.isArray(asyncHrefCards) && asyncHrefCards.map(link => /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    key: link.title
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      size: "xxl",
      type: link.icon
    }),
    "data-test-subj": "fileDataVisLink",
    title: link.title,
    description: link.description,
    href: link.href
  }))));
};
exports.ResultsLinks = ResultsLinks;
async function getFullTimeRange(index, timeFieldName, {
  getTimeFieldRange
}) {
  const query = {
    bool: {
      must: [{
        query_string: {
          analyze_wildcard: true,
          query: '*'
        }
      }]
    }
  };
  const resp = await getTimeFieldRange(index, query, timeFieldName);
  return {
    from: (0, _moment.default)(resp.start.epoch).toISOString(),
    to: (0, _moment.default)(resp.end.epoch).toISOString()
  };
}