"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.runClone = runClone;
exports.runQuickSave = runQuickSave;
exports.runSaveAs = runSaveAs;
var _react = _interopRequireDefault(require("react"));
var _reactRedux = require("react-redux");
var _public = require("@kbn/saved-objects-plugin/public");
var _ebtTools = require("@kbn/ebt-tools");
var _dashboard_constants = require("../../../dashboard_constants");
var _save_modal = require("./overlays/save_modal");
var _plugin_services = require("../../../services/plugin_services");
var _extract_title_and_count = require("./lib/extract_title_and_count");
/*
 * 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.
 */

function runSaveAs() {
  const {
    data: {
      query: {
        timefilter: {
          timefilter
        }
      }
    },
    savedObjectsTagging: {
      hasApi: hasSavedObjectsTagging
    },
    dashboardContentManagement: {
      checkForDuplicateDashboardTitle,
      saveDashboardState
    }
  } = _plugin_services.pluginServices.getServices();
  const {
    explicitInput: currentState,
    componentState: {
      lastSavedId,
      managed
    }
  } = this.getState();
  return new Promise(resolve => {
    var _currentState$descrip;
    if (managed) resolve(undefined);
    const onSave = async ({
      newTags,
      newTitle,
      newDescription,
      newCopyOnSave,
      newTimeRestore,
      onTitleDuplicate,
      isTitleDuplicateConfirmed
    }) => {
      const saveOptions = {
        confirmOverwrite: false,
        isTitleDuplicateConfirmed,
        onTitleDuplicate,
        saveAsCopy: newCopyOnSave
      };
      const stateFromSaveModal = {
        title: newTitle,
        tags: [],
        description: newDescription,
        timeRestore: newTimeRestore,
        timeRange: newTimeRestore ? timefilter.getTime() : undefined,
        refreshInterval: newTimeRestore ? timefilter.getRefreshInterval() : undefined
      };
      if (hasSavedObjectsTagging && newTags) {
        // remove `hasSavedObjectsTagging` once the savedObjectsTagging service is optional
        stateFromSaveModal.tags = newTags;
      }
      if (!(await checkForDuplicateDashboardTitle({
        title: newTitle,
        onTitleDuplicate,
        lastSavedTitle: currentState.title,
        copyOnSave: newCopyOnSave,
        isTitleDuplicateConfirmed
      }))) {
        // do not save if title is duplicate and is unconfirmed
        return {};
      }
      const stateToSave = {
        ...currentState,
        ...stateFromSaveModal
      };
      const beforeAddTime = window.performance.now();
      const saveResult = await saveDashboardState({
        currentState: stateToSave,
        saveOptions,
        lastSavedId
      });
      const addDuration = window.performance.now() - beforeAddTime;
      (0, _ebtTools.reportPerformanceMetricEvent)(_plugin_services.pluginServices.getServices().analytics, {
        eventName: _dashboard_constants.SAVED_OBJECT_POST_TIME,
        duration: addDuration,
        meta: {
          saved_object_type: _dashboard_constants.DASHBOARD_CONTENT_ID
        }
      });
      stateFromSaveModal.lastSavedId = saveResult.id;
      if (saveResult.id) {
        (0, _reactRedux.batch)(() => {
          this.dispatch.setStateFromSaveModal(stateFromSaveModal);
          this.dispatch.setLastSavedInput(stateToSave);
        });
      }
      resolve(saveResult);
      return saveResult;
    };
    const dashboardSaveModal = /*#__PURE__*/_react.default.createElement(_save_modal.DashboardSaveModal, {
      tags: currentState.tags,
      title: currentState.title,
      onClose: () => resolve(undefined),
      timeRestore: currentState.timeRestore,
      description: (_currentState$descrip = currentState.description) !== null && _currentState$descrip !== void 0 ? _currentState$descrip : '',
      showCopyOnSave: lastSavedId ? true : false,
      onSave: onSave
    });
    this.clearOverlays();
    (0, _public.showSaveModal)(dashboardSaveModal);
  });
}

/**
 * Save the current state of this dashboard to a saved object without showing any save modal.
 */
async function runQuickSave() {
  const {
    dashboardContentManagement: {
      saveDashboardState
    }
  } = _plugin_services.pluginServices.getServices();
  const {
    explicitInput: currentState,
    componentState: {
      lastSavedId,
      managed
    }
  } = this.getState();
  if (managed) return;
  const saveResult = await saveDashboardState({
    lastSavedId,
    currentState,
    saveOptions: {}
  });
  this.dispatch.setLastSavedInput(currentState);
  return saveResult;
}
async function runClone() {
  const {
    dashboardContentManagement: {
      saveDashboardState,
      checkForDuplicateDashboardTitle
    }
  } = _plugin_services.pluginServices.getServices();
  const {
    explicitInput: currentState
  } = this.getState();
  return new Promise(async (resolve, reject) => {
    try {
      const [baseTitle, baseCount] = (0, _extract_title_and_count.extractTitleAndCount)(currentState.title);
      let copyCount = baseCount;
      let newTitle = `${baseTitle} (${copyCount})`;
      while (!(await checkForDuplicateDashboardTitle({
        title: newTitle,
        lastSavedTitle: currentState.title,
        copyOnSave: true,
        isTitleDuplicateConfirmed: false
      }))) {
        copyCount++;
        newTitle = `${baseTitle} (${copyCount})`;
      }
      const saveResult = await saveDashboardState({
        saveOptions: {
          saveAsCopy: true
        },
        currentState: {
          ...currentState,
          title: newTitle
        }
      });
      resolve(saveResult);
      return saveResult.id ? {
        id: saveResult.id
      } : {
        error: saveResult.error
      };
    } catch (error) {
      reject(error);
    }
  });
}