"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "useModal", {
    enumerable: true,
    get: function() {
        return useModal;
    }
});
var _react = require("react");
var _ModalContext = require("../ModalContext");
var _Popup = require("../../Popup");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
var ESCAPE_KEYCODE = 27;
var useModal = function useModal(param) {
    var id = param.id, popupInfo = param.popupInfo, onEscKeyDown = param.onEscKeyDown, onClose = param.onClose, _param_closeOnEsc = param.closeOnEsc, closeOnEsc = _param_closeOnEsc === void 0 ? true : _param_closeOnEsc;
    var popupController = (0, _Popup.usePopupContext)();
    // При ESC закрывает текущее окно, если это возможно
    var onKeyDown = (0, _react.useCallback)(function(event) {
        if (!closeOnEsc) {
            return;
        }
        if (event.keyCode === ESCAPE_KEYCODE && (0, _ModalContext.getIdLastModal)(Array.from(popupController.items.values())) === id) {
            if (onEscKeyDown) {
                onEscKeyDown(event);
                return;
            }
            if (onClose) {
                onClose();
            }
        }
    }, [
        onClose,
        onEscKeyDown,
        popupController.items,
        closeOnEsc
    ]);
    (0, _react.useEffect)(function() {
        window.addEventListener('keydown', onKeyDown);
        return function() {
            window.removeEventListener('keydown', onKeyDown);
        };
    }, [
        onClose,
        onEscKeyDown,
        popupController.items,
        closeOnEsc
    ]);
    var modalInfo = _object_spread({
        id: id,
        info: {
            isModal: true
        }
    }, popupInfo);
    return {
        modalInfo: modalInfo
    };
};
