"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useUninstallPackage = exports.useSetPackageInstallStatus = exports.useInstallPackage = exports.useGetPackageInstallStatus = exports.PackageInstallProvider = void 0;
var _constate = _interopRequireDefault(require("constate"));
var _react = _interopRequireWildcard(require("react"));
var _reactRouterDom = require("react-router-dom");
var _i18nReact = require("@kbn/i18n-react");
var _public = require("@kbn/kibana-react-plugin/public");
var _hooks = require("../../../hooks");
var _types = require("../../../types");
var _services = require("../services");
var _ = require(".");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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.
 */

// TODO: Refactor this away from constate, which is unmaintained, as this is the only
// usage of it across the Fleet codebase

function usePackageInstall({
  notifications,
  theme$
}) {
  const history = (0, _reactRouterDom.useHistory)();
  const {
    getPath
  } = (0, _hooks.useLink)();
  const [packages, setPackage] = (0, _react.useState)({});
  const confirmForceInstall = (0, _.useConfirmForceInstall)();
  const setPackageInstallStatus = (0, _react.useCallback)(({
    name,
    status,
    version
  }) => {
    const packageProps = {
      status,
      version
    };
    setPackage(prev => ({
      ...prev,
      [name]: packageProps
    }));
  }, []);
  const getPackageInstallStatus = (0, _react.useCallback)(pkg => {
    return packages[pkg];
  }, [packages]);
  const optionallyForceInstall = async (installProps, prevStatus) => {
    const forceInstall = await confirmForceInstall(installProps);
    if (forceInstall) {
      installPackage({
        ...installProps,
        force: true
      });
    } else {
      setPackageInstallStatus({
        ...prevStatus,
        name: installProps.name
      });
    }
  };
  const installPackage = (0, _react.useCallback)(async props => {
    const {
      name,
      version,
      title,
      fromUpdate = false,
      isReinstall = false,
      force = false
    } = props;
    const prevStatus = getPackageInstallStatus(name);
    const newStatus = {
      ...prevStatus,
      name,
      status: isReinstall ? _types.InstallStatus.reinstalling : _types.InstallStatus.installing
    };
    setPackageInstallStatus(newStatus);
    const res = await (0, _hooks.sendInstallPackage)(name, version, isReinstall || force);
    if (res.error) {
      if ((0, _services.isVerificationError)(res.error)) {
        return optionallyForceInstall(props, prevStatus);
      }
      if (fromUpdate) {
        // if there is an error during update, set it back to the previous version
        // as handling of bad update is not implemented yet
        setPackageInstallStatus({
          ...prevStatus,
          name
        });
      } else {
        setPackageInstallStatus({
          name,
          status: _types.InstallStatus.notInstalled,
          version
        });
      }
      notifications.toasts.addWarning({
        title: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageInstallErrorTitle",
          defaultMessage: "Failed to install {title} package",
          values: {
            title
          }
        }), {
          theme$
        }),
        text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageInstallErrorDescription",
          defaultMessage: "Something went wrong while trying to install this package. Please try again later."
        }), {
          theme$
        }),
        iconType: 'error'
      });
    } else {
      setPackageInstallStatus({
        name,
        status: _types.InstallStatus.installed,
        version
      });
      if (fromUpdate) {
        const settingsPath = getPath('integration_details_settings', {
          pkgkey: `${name}-${version}`
        });
        history.push(settingsPath);
      }
      if (isReinstall) {
        notifications.toasts.addSuccess({
          title: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.integrations.packageReinstallSuccessTitle",
            defaultMessage: "Reinstalled {title}",
            values: {
              title
            }
          }), {
            theme$
          }),
          text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.integrations.packageReinstallSuccessDescription",
            defaultMessage: "Successfully reinstalled {title}",
            values: {
              title
            }
          }), {
            theme$
          })
        });
      } else {
        notifications.toasts.addSuccess({
          title: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.integrations.packageInstallSuccessTitle",
            defaultMessage: "Installed {title}",
            values: {
              title
            }
          }), {
            theme$
          }),
          text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.integrations.packageInstallSuccessDescription",
            defaultMessage: "Successfully installed {title}",
            values: {
              title
            }
          }), {
            theme$
          })
        });
      }
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [getPackageInstallStatus, setPackageInstallStatus, notifications.toasts, theme$, getPath, history]);
  const uninstallPackage = (0, _react.useCallback)(async ({
    name,
    version,
    title,
    redirectToVersion
  }) => {
    setPackageInstallStatus({
      name,
      status: _types.InstallStatus.uninstalling,
      version
    });
    const res = await (0, _hooks.sendRemovePackage)(name, version);
    if (res.error) {
      setPackageInstallStatus({
        name,
        status: _types.InstallStatus.installed,
        version
      });
      notifications.toasts.addWarning({
        title: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageUninstallErrorTitle",
          defaultMessage: "Failed to uninstall {title} package",
          values: {
            title
          }
        }), {
          theme$
        }),
        text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageUninstallErrorDescription",
          defaultMessage: "Something went wrong while trying to uninstall this package. Please try again later."
        }), {
          theme$
        }),
        iconType: 'error'
      });
    } else {
      setPackageInstallStatus({
        name,
        status: _types.InstallStatus.notInstalled,
        version: null
      });
      notifications.toasts.addSuccess({
        title: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageUninstallSuccessTitle",
          defaultMessage: "Uninstalled {title}",
          values: {
            title
          }
        }), {
          theme$
        }),
        text: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.fleet.integrations.packageUninstallSuccessDescription",
          defaultMessage: "Successfully uninstalled {title}",
          values: {
            title
          }
        }), {
          theme$
        })
      });
      if (redirectToVersion !== version) {
        const settingsPath = getPath('integration_details_settings', {
          pkgkey: `${name}-${redirectToVersion}`
        });
        history.push(settingsPath);
      }
    }
  }, [notifications.toasts, setPackageInstallStatus, getPath, history, theme$]);
  return {
    packages,
    installPackage,
    setPackageInstallStatus,
    getPackageInstallStatus,
    uninstallPackage
  };
}
const [PackageInstallProvider, useInstallPackage, useSetPackageInstallStatus, useGetPackageInstallStatus, useUninstallPackage] = (0, _constate.default)(usePackageInstall, value => value.installPackage, value => value.setPackageInstallStatus, value => value.getPackageInstallStatus, value => value.uninstallPackage);
exports.useUninstallPackage = useUninstallPackage;
exports.useGetPackageInstallStatus = useGetPackageInstallStatus;
exports.useSetPackageInstallStatus = useSetPackageInstallStatus;
exports.useInstallPackage = useInstallPackage;
exports.PackageInstallProvider = PackageInstallProvider;