"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.servicesReady = exports.resolveServicesReady = exports.DashboardPlugin = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _i18n = require("@kbn/i18n");
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _public = require("@kbn/core/public");
var _common = require("@kbn/kibana-utils-plugin/common");
var _public2 = require("@kbn/kibana-utils-plugin/public");
var _dashboard_container_factory = require("./dashboard_container/embeddable/dashboard_container_factory");
var _locator = require("./dashboard_app/locator/locator");
var _dashboard_constants = require("./dashboard_constants");
var _content_management = require("../common/content_management");
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.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
let resolveServicesReady;
exports.resolveServicesReady = resolveServicesReady;
const servicesReady = new Promise(resolve => exports.resolveServicesReady = resolveServicesReady = resolve);
exports.servicesReady = servicesReady;
class DashboardPlugin {
  constructor(initializerContext) {
    (0, _defineProperty2.default)(this, "appStateUpdater", new _rxjs.BehaviorSubject(() => ({})));
    (0, _defineProperty2.default)(this, "stopUrlTracking", undefined);
    (0, _defineProperty2.default)(this, "currentHistory", undefined);
    (0, _defineProperty2.default)(this, "dashboardFeatureFlagConfig", void 0);
    (0, _defineProperty2.default)(this, "locator", void 0);
    this.initializerContext = initializerContext;
  }
  async startDashboardKibanaServices(coreStart, startPlugins, initContext) {
    const {
      registry,
      pluginServices
    } = await Promise.resolve().then(() => _interopRequireWildcard(require('./services/plugin_services')));
    pluginServices.setRegistry(registry.start({
      coreStart,
      startPlugins,
      initContext
    }));
    resolveServicesReady();
  }
  setup(core, {
    share,
    embeddable,
    home,
    urlForwarding,
    data,
    contentManagement
  }) {
    this.dashboardFeatureFlagConfig = this.initializerContext.config.get();
    if (share) {
      this.locator = share.url.locators.create(new _locator.DashboardAppLocatorDefinition({
        useHashedUrl: core.uiSettings.get('state:storeInSessionStorage'),
        getDashboardFilterFields: async dashboardId => {
          var _await$loadDashboardS, _await$loadDashboardS2;
          const {
            pluginServices
          } = await Promise.resolve().then(() => _interopRequireWildcard(require('./services/plugin_services')));
          const {
            dashboardContentManagement: {
              loadDashboardState
            }
          } = pluginServices.getServices();
          return (_await$loadDashboardS = (_await$loadDashboardS2 = (await loadDashboardState({
            id: dashboardId
          })).dashboardInput) === null || _await$loadDashboardS2 === void 0 ? void 0 : _await$loadDashboardS2.filters) !== null && _await$loadDashboardS !== void 0 ? _await$loadDashboardS : [];
        }
      }));
    }
    const {
      appMounted,
      appUnMounted,
      stop: stopUrlTracker,
      restorePreviousUrl
    } = (0, _public2.createKbnUrlTracker)({
      baseUrl: core.http.basePath.prepend('/app/dashboards'),
      defaultSubUrl: `#${_dashboard_constants.LANDING_PAGE_PATH}`,
      storageKey: `lastUrl:${core.http.basePath.get()}:dashboard`,
      navLinkUpdater$: this.appStateUpdater,
      toastNotifications: core.notifications.toasts,
      stateParams: [{
        kbnUrlKey: '_g',
        stateUpdate$: data.query.state$.pipe((0, _operators.filter)(({
          changes
        }) => !!(changes.globalFilters || changes.time || changes.refreshInterval)), (0, _operators.map)(async ({
          state
        }) => {
          var _state$filters;
          const {
            isFilterPinned
          } = await Promise.resolve().then(() => _interopRequireWildcard(require('@kbn/es-query')));
          return {
            ...state,
            filters: (_state$filters = state.filters) === null || _state$filters === void 0 ? void 0 : _state$filters.filter(isFilterPinned)
          };
        }))
      }],
      getHistory: () => this.currentHistory,
      onBeforeNavLinkSaved: newNavLink => {
        // Do not save SEARCH_SESSION_ID into nav link, because of possible edge cases
        // that could lead to session restoration failure.
        // see: https://github.com/elastic/kibana/issues/87149

        // We also don't want to store the table list view state.
        // The question is: what _do_ we want to save here? :)
        const tableListUrlState = ['s', 'title', 'sort', 'sortdir'];
        return (0, _common.replaceUrlHashQuery)(newNavLink, query => {
          [_dashboard_constants.SEARCH_SESSION_ID, ...tableListUrlState].forEach(param => {
            delete query[param];
          });
          return query;
        });
      }
    });
    core.getStartServices().then(([, deps]) => {
      const dashboardContainerFactory = new _dashboard_container_factory.DashboardContainerFactoryDefinition(deps.embeddable);
      embeddable.registerEmbeddableFactory(dashboardContainerFactory.type, dashboardContainerFactory);
    });
    this.stopUrlTracking = () => {
      stopUrlTracker();
    };
    const app = {
      id: _dashboard_constants.DASHBOARD_APP_ID,
      title: 'Dashboard',
      order: 2500,
      euiIconType: 'logoKibana',
      defaultPath: `#${_dashboard_constants.LANDING_PAGE_PATH}`,
      updater$: this.appStateUpdater,
      category: _public.DEFAULT_APP_CATEGORIES.kibana,
      mount: async params => {
        this.currentHistory = params.history;
        params.element.classList.add(_public.APP_WRAPPER_CLASS);
        const {
          mountApp
        } = await Promise.resolve().then(() => _interopRequireWildcard(require('./dashboard_app/dashboard_router')));
        appMounted();
        const mountContext = {
          restorePreviousUrl,
          scopedHistory: () => this.currentHistory,
          onAppLeave: params.onAppLeave,
          setHeaderActionMenu: params.setHeaderActionMenu
        };
        return mountApp({
          core,
          appUnMounted,
          element: params.element,
          mountContext
        });
      }
    };
    core.application.register(app);
    urlForwarding.forwardApp(_dashboard_constants.DASHBOARD_APP_ID, _dashboard_constants.DASHBOARD_APP_ID, path => {
      const [, tail] = /(\?.*)/.exec(path) || [];
      // carry over query if it exists
      return `#/list${tail || ''}`;
    });
    urlForwarding.forwardApp(_dashboard_constants.LEGACY_DASHBOARD_APP_ID, _dashboard_constants.DASHBOARD_APP_ID, path => {
      const [, id, tail] = /dashboard\/?(.*?)($|\?.*)/.exec(path) || [];
      if (!id && !tail) {
        // unrecognized sub url
        return '#/list';
      }
      if (!id && tail) {
        // unsaved dashboard, but probably state in URL
        return `#/create${tail || ''}`;
      }
      // persisted dashboard, probably with url state
      return `#/view/${id}${tail || ''}`;
    });
    const dashboardAppTitle = _i18n.i18n.translate('dashboard.featureCatalogue.dashboardTitle', {
      defaultMessage: 'Dashboard'
    });
    if (home) {
      home.featureCatalogue.register({
        id: _dashboard_constants.DASHBOARD_APP_ID,
        title: dashboardAppTitle,
        subtitle: _i18n.i18n.translate('dashboard.featureCatalogue.dashboardSubtitle', {
          defaultMessage: 'Analyze data in dashboards.'
        }),
        description: _i18n.i18n.translate('dashboard.featureCatalogue.dashboardDescription', {
          defaultMessage: 'Display and share a collection of visualizations and saved searches.'
        }),
        icon: 'dashboardApp',
        path: `/app/${_dashboard_constants.DASHBOARD_APP_ID}#${_dashboard_constants.LANDING_PAGE_PATH}`,
        showOnHomePage: false,
        category: 'data',
        solutionId: 'kibana',
        order: 100
      });
    }

    // register content management
    contentManagement.registry.register({
      id: _content_management.CONTENT_ID,
      version: {
        latest: _content_management.LATEST_VERSION
      },
      name: dashboardAppTitle
    });
    return {
      locator: this.locator
    };
  }
  start(core, plugins) {
    this.startDashboardKibanaServices(core, plugins, this.initializerContext).then(async () => {
      var _this$dashboardFeatur;
      const {
        buildAllDashboardActions
      } = await Promise.resolve().then(() => _interopRequireWildcard(require('./dashboard_actions')));
      buildAllDashboardActions({
        core,
        plugins,
        allowByValueEmbeddables: (_this$dashboardFeatur = this.dashboardFeatureFlagConfig) === null || _this$dashboardFeatur === void 0 ? void 0 : _this$dashboardFeatur.allowByValueEmbeddables
      });
    });
    return {
      locator: this.locator,
      dashboardFeatureFlagConfig: this.dashboardFeatureFlagConfig,
      findDashboardsService: async () => {
        const {
          pluginServices
        } = await Promise.resolve().then(() => _interopRequireWildcard(require('./services/plugin_services')));
        const {
          dashboardContentManagement: {
            findDashboards
          }
        } = pluginServices.getServices();
        return findDashboards;
      }
    };
  }
  stop() {
    if (this.stopUrlTracking) {
      this.stopUrlTracking();
    }
  }
}
exports.DashboardPlugin = DashboardPlugin;