"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaultEmbeddableFactoryProvider = void 0;
var _run_factory_migrations = require("../factory_migrations/run_factory_migrations");
/*
 * 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 defaultEmbeddableFactoryProvider = def => {
  var _def$isContainerType;
  if (def.migrations && !def.latestVersion) {
    throw new Error('To run clientside Embeddable migrations a latest version key is required on the factory');
  }
  const factory = {
    ...def,
    latestVersion: def.latestVersion,
    isContainerType: (_def$isContainerType = def.isContainerType) !== null && _def$isContainerType !== void 0 ? _def$isContainerType : false,
    canCreateNew: def.canCreateNew ? def.canCreateNew.bind(def) : () => true,
    getDefaultInput: def.getDefaultInput ? def.getDefaultInput.bind(def) : () => ({}),
    getExplicitInput: def.getExplicitInput ? def.getExplicitInput.bind(def) : () => Promise.resolve({}),
    createFromSavedObject: def.createFromSavedObject ? def.createFromSavedObject.bind(def) : (savedObjectId, input, parent) => {
      throw new Error(`Creation from saved object not supported by type ${def.type}`);
    },
    create: (...args) => {
      const [initialInput, ...otherArgs] = args;
      const {
        input
      } = (0, _run_factory_migrations.runEmbeddableFactoryMigrations)(initialInput, def);
      const createdEmbeddable = def.create.bind(def)(input, ...otherArgs);
      return createdEmbeddable;
    },
    type: def.type,
    isEditable: def.isEditable.bind(def),
    getDisplayName: def.getDisplayName.bind(def),
    getDescription: def.getDescription ? def.getDescription.bind(def) : () => '',
    getIconType: def.getIconType ? def.getIconType.bind(def) : () => 'empty',
    savedObjectMetaData: def.savedObjectMetaData,
    telemetry: def.telemetry || ((state, stats) => stats),
    inject: def.inject || (state => state),
    extract: def.extract || (state => ({
      state,
      references: []
    })),
    migrations: def.migrations || {},
    grouping: def.grouping
  };
  return factory;
};
exports.defaultEmbeddableFactoryProvider = defaultEmbeddableFactoryProvider;