"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ClonePanelAction = exports.ACTION_CLONE_PANEL = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _uuid = require("uuid");
var _lodash = require("lodash");
var _public = require("@kbn/embeddable-plugin/public");
var _public2 = require("@kbn/ui-actions-plugin/public");
var _plugin_services = require("../services/plugin_services");
var _dashboard_actions_strings = require("./_dashboard_actions_strings");
var _panel_placement = require("../dashboard_container/component/panel_placement");
var _dashboard_container = require("../dashboard_container");
/*
 * 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 ACTION_CLONE_PANEL = 'clonePanel';
exports.ACTION_CLONE_PANEL = ACTION_CLONE_PANEL;
class ClonePanelAction {
  constructor() {
    (0, _defineProperty2.default)(this, "type", ACTION_CLONE_PANEL);
    (0, _defineProperty2.default)(this, "id", ACTION_CLONE_PANEL);
    (0, _defineProperty2.default)(this, "order", 45);
    (0, _defineProperty2.default)(this, "toastsService", void 0);
    ({
      notifications: {
        toasts: this.toastsService
      }
    } = _plugin_services.pluginServices.getServices());
  }
  getDisplayName({
    embeddable
  }) {
    if (!embeddable.getRoot() || !embeddable.getRoot().isContainer) {
      throw new _public2.IncompatibleActionError();
    }
    return _dashboard_actions_strings.dashboardClonePanelActionStrings.getDisplayName();
  }
  getIconType({
    embeddable
  }) {
    if (!embeddable.getRoot() || !embeddable.getRoot().isContainer) {
      throw new _public2.IncompatibleActionError();
    }
    return 'copy';
  }
  async isCompatible({
    embeddable
  }) {
    var _embeddable$getInput;
    return Boolean(!(0, _public.isErrorEmbeddable)(embeddable) && ((_embeddable$getInput = embeddable.getInput()) === null || _embeddable$getInput === void 0 ? void 0 : _embeddable$getInput.viewMode) !== _public.ViewMode.VIEW && embeddable.getRoot() && embeddable.getRoot().isContainer && embeddable.getRoot().type === _dashboard_container.DASHBOARD_CONTAINER_TYPE && embeddable.getOutput().editable);
  }
  async execute({
    embeddable
  }) {
    if (!embeddable.getRoot() || !embeddable.getRoot().isContainer) {
      throw new _public2.IncompatibleActionError();
    }
    const dashboard = embeddable.getRoot();
    const panelToClone = dashboard.getInput().panels[embeddable.id];
    if (!panelToClone) {
      throw new _public.PanelNotFoundError();
    }

    // Clone panel input
    const clonedPanelState = await (async () => {
      const newTitle = await this.getCloneTitle(embeddable, embeddable.getTitle() || '');
      const id = (0, _uuid.v4)();
      if ((0, _public.isReferenceOrValueEmbeddable)(embeddable)) {
        return {
          type: embeddable.type,
          explicitInput: {
            ...(await embeddable.getInputAsValueType()),
            hidePanelTitles: panelToClone.explicitInput.hidePanelTitles,
            ...(newTitle ? {
              title: newTitle
            } : {}),
            id
          }
        };
      }
      return {
        type: embeddable.type,
        explicitInput: {
          ...panelToClone.explicitInput,
          title: newTitle,
          id
        }
      };
    })();
    this.toastsService.addSuccess({
      title: _dashboard_actions_strings.dashboardClonePanelActionStrings.getSuccessMessage(),
      'data-test-subj': 'addObjectToContainerSuccess'
    });
    const {
      newPanelPlacement,
      otherPanels
    } = (0, _panel_placement.placeClonePanel)({
      width: panelToClone.gridData.w,
      height: panelToClone.gridData.h,
      currentPanels: dashboard.getInput().panels,
      placeBesideId: panelToClone.explicitInput.id
    });
    const newPanel = {
      ...clonedPanelState,
      gridData: {
        ...newPanelPlacement,
        i: clonedPanelState.explicitInput.id
      }
    };
    dashboard.updateInput({
      panels: {
        ...otherPanels,
        [newPanel.explicitInput.id]: newPanel
      }
    });
  }
  async getCloneTitle(embeddable, rawTitle) {
    if (rawTitle === '') return ''; // If

    const clonedTag = _dashboard_actions_strings.dashboardClonePanelActionStrings.getClonedTag();
    const cloneRegex = new RegExp(`\\(${clonedTag}\\)`, 'g');
    const cloneNumberRegex = new RegExp(`\\(${clonedTag} [0-9]+\\)`, 'g');
    const baseTitle = rawTitle.replace(cloneNumberRegex, '').replace(cloneRegex, '').trim();
    const dashboard = embeddable.getRoot();
    const similarTitles = (0, _lodash.filter)(await dashboard.getPanelTitles(), title => {
      return title.startsWith(baseTitle);
    });
    const cloneNumbers = (0, _lodash.map)(similarTitles, title => {
      if (title.match(cloneRegex)) return 0;
      const cloneTag = title.match(cloneNumberRegex);
      return cloneTag ? parseInt(cloneTag[0].replace(/[^0-9.]/g, ''), 10) : -1;
    });
    const similarBaseTitlesCount = (0, _lodash.max)(cloneNumbers) || 0;
    return similarBaseTitlesCount < 0 ? baseTitle + ` (${clonedTag})` : baseTitle + ` (${clonedTag} ${similarBaseTitlesCount + 1})`;
  }
}
exports.ClonePanelAction = ClonePanelAction;