"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CollectConfigContainer = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _lodash = require("lodash");
var _dashboard_drilldown_config = require("./dashboard_drilldown_config");
var _i18n = require("./i18n");
/*
 * 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 mergeDashboards = (dashboards, selectedDashboard) => {
  // if we have a selected dashboard and its not in the list, append it
  if (selectedDashboard && (0, _lodash.findIndex)(dashboards, {
    value: selectedDashboard.value
  }) === -1) {
    return [selectedDashboard, ...dashboards];
  }
  return dashboards;
};
const dashboardSavedObjectToMenuItem = savedObject => ({
  value: savedObject.id,
  label: savedObject.attributes.title
});
class CollectConfigContainer extends _react.default.Component {
  constructor(props) {
    super(props);
    (0, _defineProperty2.default)(this, "isMounted", true);
    (0, _defineProperty2.default)(this, "state", {
      dashboards: [],
      isLoading: false,
      searchString: undefined,
      selectedDashboard: undefined,
      error: undefined
    });
    (0, _defineProperty2.default)(this, "debouncedLoadDashboards", void 0);
    this.debouncedLoadDashboards = (0, _lodash.debounce)(this.loadDashboards.bind(this), 500);
  }
  componentDidMount() {
    this.loadSelectedDashboard();
    this.loadDashboards();
  }
  componentWillUnmount() {
    this.isMounted = false;
  }
  render() {
    const {
      config,
      onConfig
    } = this.props;
    const {
      dashboards,
      selectedDashboard,
      isLoading,
      error
    } = this.state;
    return /*#__PURE__*/_react.default.createElement(_dashboard_drilldown_config.DashboardDrilldownConfig, {
      dashboards: mergeDashboards(dashboards, selectedDashboard),
      isLoading: isLoading,
      error: error,
      onDashboardSelect: dashboardId => {
        onConfig({
          ...config,
          dashboardId
        });
        if (this.state.error) {
          this.setState({
            error: undefined
          });
        }
      },
      onSearchChange: this.debouncedLoadDashboards,
      config: config,
      onConfigChange: changes => {
        onConfig({
          ...config,
          ...changes
        });
      }
    });
  }
  async loadSelectedDashboard() {
    var _savedObject$error;
    const {
      config,
      params: {
        start
      }
    } = this.props;
    if (!config.dashboardId) return;
    const savedObject = await start().core.savedObjects.client.get('dashboard', config.dashboardId);
    if (!this.isMounted) return;

    // handle case when destination dashboard no longer exists
    if (((_savedObject$error = savedObject.error) === null || _savedObject$error === void 0 ? void 0 : _savedObject$error.statusCode) === 404) {
      this.setState({
        error: (0, _i18n.txtDestinationDashboardNotFound)(config.dashboardId)
      });
      this.props.onConfig({
        ...config,
        dashboardId: undefined
      });
      return;
    }
    if (savedObject.error) {
      this.setState({
        error: savedObject.error.message
      });
      this.props.onConfig({
        ...config,
        dashboardId: undefined
      });
      return;
    }
    this.setState({
      selectedDashboard: dashboardSavedObjectToMenuItem(savedObject)
    });
  }
  async loadDashboards(searchString) {
    this.setState({
      searchString,
      isLoading: true
    });
    const savedObjectsClient = this.props.params.start().core.savedObjects.client;
    const {
      savedObjects
    } = await savedObjectsClient.find({
      type: 'dashboard',
      search: searchString ? `${searchString}*` : undefined,
      searchFields: ['title^3', 'description'],
      defaultSearchOperator: 'AND',
      perPage: 100
    });

    // bail out if this response is no longer needed
    if (!this.isMounted) return;
    if (searchString !== this.state.searchString) return;
    const dashboardList = savedObjects.map(dashboardSavedObjectToMenuItem);
    this.setState({
      dashboards: dashboardList,
      isLoading: false
    });
  }
}
exports.CollectConfigContainer = CollectConfigContainer;