"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useIncomingEmbeddable = void 0;
var _react = require("react");
var _reactRedux = require("react-redux");
var _interpreter = require("@kbn/interpreter");
var _i18n = require("../../../../i18n");
var _lib = require("../../../../common/lib");
var _embeddable_dataurl = require("../../../../common/lib/embeddable_dataurl");
var _services = require("../../../services");
var _elements = require("../../../state/actions/elements");
var _transient = require("../../../state/actions/transient");
var _embeddable = require("../../../state/actions/embeddable");
var _resolved_args = require("../../../state/actions/resolved_args");
/*
 * 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.
 */

// @ts-expect-error unconverted file

// @ts-expect-error unconverted file

const {
  actionsElements: strings
} = _i18n.ErrorStrings;
const useIncomingEmbeddable = selectedPage => {
  const embeddablesService = (0, _services.useEmbeddablesService)();
  const labsService = (0, _services.useLabsService)();
  const dispatch = (0, _reactRedux.useDispatch)();
  const notifyService = (0, _services.useNotifyService)();
  const isByValueEnabled = labsService.isProjectEnabled('labs:canvas:byValueEmbeddable');
  const stateTransferService = embeddablesService.getStateTransfer();

  // fetch incoming embeddable from state transfer service.
  const incomingEmbeddable = stateTransferService.getIncomingEmbeddablePackage(_lib.CANVAS_APP, true);
  (0, _react.useEffect)(() => {
    if (isByValueEnabled && incomingEmbeddable) {
      const {
        embeddableId,
        input: incomingInput,
        type
      } = incomingEmbeddable;

      // retrieve existing element
      const originalElement = selectedPage.elements.find(({
        id
      }) => id === embeddableId);
      if (originalElement) {
        const originalAst = (0, _interpreter.fromExpression)(originalElement.expression);
        const functionIndex = originalAst.chain.findIndex(({
          function: fn
        }) => ['embeddable', 'savedVisualization'].includes(fn));
        if (functionIndex === -1) {
          dispatch((0, _elements.fetchAllRenderables)());
          return;
        }
        if (originalAst.chain[functionIndex].function === 'savedVisualization') {
          notifyService.error(strings.getConvertToLensUnsupportedSavedVisualization());
          dispatch((0, _elements.fetchAllRenderables)());
          return;
        }
        const originalInput = (0, _embeddable_dataurl.decode)(originalAst.chain[functionIndex].arguments.config[0]);
        const originalType = originalAst.chain[functionIndex].arguments.type[0];

        // clear out resolved arg for old embeddable
        const argumentPath = [embeddableId, 'expressionRenderable'];
        dispatch((0, _resolved_args.clearValue)({
          path: argumentPath
        }));
        let updatedInput;

        // if type was changed, we should not provide originalInput
        if (originalType !== type) {
          updatedInput = incomingInput;
        } else {
          updatedInput = {
            ...originalInput,
            ...incomingInput
          };
        }
        const expression = `embeddable config="${(0, _embeddable_dataurl.encode)(updatedInput)}"
  type="${type}"
| render`;
        dispatch((0, _embeddable.updateEmbeddableExpression)({
          elementId: originalElement.id,
          embeddableExpression: expression
        }));

        // update resolved args
        dispatch((0, _embeddable.fetchEmbeddableRenderable)(originalElement.id));

        // select new embeddable element
        dispatch((0, _transient.selectToplevelNodes)([embeddableId]));
      } else {
        const expression = `embeddable config="${(0, _embeddable_dataurl.encode)(incomingInput)}"
  type="${type}"
| render`;
        dispatch((0, _elements.addElement)(selectedPage.id, {
          expression
        }));
      }
    }
  }, [dispatch, notifyService, selectedPage, incomingEmbeddable, isByValueEnabled]);
};
exports.useIncomingEmbeddable = useIncomingEmbeddable;