"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useHistoryBlock = useHistoryBlock;
var _react = require("react");
var _reactRouterDom = require("react-router-dom");
var _i18n = require("@kbn/i18n");
var _hooks = require("../../../../hooks");
/*
 * 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.
 */

function useHistoryBlock(isEdited) {
  const history = (0, _reactRouterDom.useHistory)();
  const {
    overlays,
    application,
    http
  } = (0, _hooks.useStartServices)();
  (0, _react.useEffect)(() => {
    if (!isEdited) {
      return;
    }
    const unblock = history.block(state => {
      async function confirmAsync() {
        const confirmRes = await overlays.openConfirm(_i18n.i18n.translate('xpack.fleet.editPackagePolicy.historyBlockDescription', {
          defaultMessage: `Unsaved changes will be discarded. Are you sure you would like to continue?`
        }), {
          title: _i18n.i18n.translate('xpack.fleet.editPackagePolicy.historyBlockTitle', {
            defaultMessage: 'Discard Changes?'
          })
        });
        if (confirmRes) {
          const url = http.basePath.prepend(state.pathname) + state.hash + state.search;
          unblock();
          application.navigateToUrl(url, {
            state: state.state
          });
        }
      }
      confirmAsync();
      return false;
    });
    return unblock;
  }, [history, isEdited, overlays, application, http.basePath]);
}