"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDiscoverCustomizationService = exports.useDiscoverCustomization$ = exports.useDiscoverCustomization = exports.DiscoverCustomizationProvider = void 0;
var _react = require("react");
var _useObservable = _interopRequireDefault(require("react-use/lib/useObservable"));
var _lodash = require("lodash");
var _useEffectOnce = _interopRequireDefault(require("react-use/lib/useEffectOnce"));
var _customization_service = require("./customization_service");
/*
 * 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 customizationContext = /*#__PURE__*/(0, _react.createContext)((0, _customization_service.createCustomizationService)());
const DiscoverCustomizationProvider = customizationContext.Provider;
exports.DiscoverCustomizationProvider = DiscoverCustomizationProvider;
const useDiscoverCustomizationService = ({
  customizationCallbacks,
  stateContainer
}) => {
  const [customizationService, setCustomizationService] = (0, _react.useState)();
  (0, _useEffectOnce.default)(() => {
    const customizations = (0, _customization_service.createCustomizationService)();
    const callbacks = customizationCallbacks.map(callback => Promise.resolve(callback({
      customizations,
      stateContainer
    })));
    const initialize = () => Promise.all(callbacks).then(result => result.filter(_lodash.isFunction));
    initialize().then(() => {
      setCustomizationService(customizations);
    });
    return () => {
      initialize().then(cleanups => {
        cleanups.forEach(cleanup => cleanup());
      });
    };
  });
  const isInitialized = Boolean(customizationService);
  return {
    customizationService,
    isInitialized
  };
};
exports.useDiscoverCustomizationService = useDiscoverCustomizationService;
const useDiscoverCustomization$ = id => (0, _react.useContext)(customizationContext).get$(id);
exports.useDiscoverCustomization$ = useDiscoverCustomization$;
const useDiscoverCustomization = id => (0, _useObservable.default)(useDiscoverCustomization$(id));
exports.useDiscoverCustomization = useDiscoverCustomization;