"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResizablePanes = void 0;
var react_1 = __importStar(require("react"));
var classnames_1 = __importDefault(require("classnames"));
var react_resizable_panels_1 = require("react-resizable-panels");
var styles_1 = require("@mui/material/styles");
var react_resize_detector_1 = __importDefault(require("react-resize-detector"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var styles_2 = require("./styles");
var HANDLE_CHANGE_DEBOUNCE_INTERVAL = 250;
var isHorizontal = function (orientation) { return orientation === 'horizontal'; };
var isEqualSize = function (a, b) { return a.toFixed(2) === b.toFixed(2); };
var ResizablePanes = function (_a) {
    var _b;
    var className = _a.className, children = _a.children, _c = _a.orientation, orientation = _c === void 0 ? 'vertical' : _c, _d = _a.primary, primary = _d === void 0 ? 'first' : _d, size = _a.size, minSize = _a.minSize, maxSize = _a.maxSize, allowResize = _a.allowResize, _e = _a.debounceInterval, debounceInterval = _e === void 0 ? HANDLE_CHANGE_DEBOUNCE_INTERVAL : _e, onChange = _a.onChange;
    var styles = (0, styles_2.useStyles)();
    var theme = (0, styles_1.useTheme)();
    var panelRef = (0, react_1.useRef)();
    var _f = (0, react_1.useState)(null), containerEl = _f[0], setContainerEl = _f[1];
    var _g = (0, react_1.useState)(0), percentageMinSize = _g[0], setPercentageMinSize = _g[1];
    var _h = (0, react_1.useState)(0), percentageMaxSize = _h[0], setPercentageMaxSize = _h[1];
    var _j = (0, react_1.useState)(true), isPaneAnimationEnabled = _j[0], setIsPaneAnimationEnabled = _j[1];
    var enableAnimation = (0, react_1.useCallback)(function () { return setIsPaneAnimationEnabled(true); }, []);
    var disableAnimation = (0, react_1.useCallback)(function () { return setIsPaneAnimationEnabled(false); }, []);
    var getContainerSize = (0, react_1.useCallback)(function () { return (isHorizontal(orientation) ? containerEl === null || containerEl === void 0 ? void 0 : containerEl.clientHeight : containerEl === null || containerEl === void 0 ? void 0 : containerEl.clientWidth); }, [containerEl, orientation]);
    if (typeof size === 'number' && size < 0) {
        size = (getContainerSize() || 0) + size;
    }
    var convertSize = (0, react_1.useCallback)(function (size) {
        if (typeof size === 'string' && size.endsWith('%')) {
            return +size.replace('%', '');
        }
        if (typeof size === 'string' && size.endsWith('px')) {
            size = size.replace('px', '');
        }
        return isNaN(+size) ? null : (+size / getContainerSize()) * 100;
    }, [getContainerSize]);
    var convertMinMaxSize = (0, react_1.useCallback)(function (size, minMaxSize) {
        if (size === 0 || size === 100)
            return 0;
        return convertSize(minMaxSize) || 0;
    }, [convertSize]);
    var actualizeSizes = (0, react_1.useCallback)(function () {
        if (containerEl && panelRef.current) {
            var convertedSize = convertSize(size);
            if (convertedSize != null && !isNaN(convertedSize)) {
                setPercentageMaxSize(convertMinMaxSize(convertedSize, maxSize));
                setPercentageMinSize(convertMinMaxSize(convertedSize, minSize));
                panelRef.current.resize(convertedSize);
            }
        }
    }, [convertSize, convertMinMaxSize, minSize, maxSize, size, containerEl]);
    (0, react_1.useEffect)(function () {
        actualizeSizes();
    }, [actualizeSizes, percentageMaxSize, percentageMinSize]);
    var handleChange = (0, react_1.useCallback)((0, mdm_sdk_1.debounce)(function (size, containerSize) {
        if (size === undefined || containerSize === 0)
            return;
        onChange({
            percentageSize: size + '%',
            isMaxSize: +percentageMaxSize > 0
                ? isEqualSize(size, percentageMaxSize)
                : isEqualSize(size, 100 + percentageMaxSize),
            isMinSize: isEqualSize(size, percentageMinSize),
            size: Math.round((size * containerSize) / 100)
        });
    }, debounceInterval), [onChange, percentageMaxSize, percentageMinSize]);
    var handleDragging = (0, react_1.useCallback)(function (isDragging) {
        if (isDragging) {
            // Why do we need handleChange() here?
            // Case - user resized panels, and then immediately started resizing again.
            // We need to prevent onChange calling with "previous" data (handleChange is debounced calling of onChange)
            handleChange();
            disableAnimation();
        }
        else {
            handleChange(panelRef.current.getSize(), getContainerSize());
            enableAnimation();
        }
    }, [disableAnimation, enableAnimation, handleChange, getContainerSize]);
    var paneAnimationStyle = (0, react_1.useMemo)(function () { return ({
        transition: theme.transitions.create('flex', {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen
        })
    }); }, [theme]);
    var primaryPanelProps = __assign(__assign({ className: styles.panel, minSize: percentageMinSize }, (percentageMaxSize > 0 ? { maxSize: percentageMaxSize } : {})), { ref: panelRef, style: isPaneAnimationEnabled ? paneAnimationStyle : undefined });
    var secondaryPanelProps = __assign({ className: styles.panel, style: isPaneAnimationEnabled ? paneAnimationStyle : undefined }, (percentageMaxSize < 0 ? { minSize: -percentageMaxSize } : {}));
    return (react_1.default.createElement("div", { ref: setContainerEl, className: (0, classnames_1.default)(styles.container, className) },
        react_1.default.createElement(react_resize_detector_1.default, { handleHeight: isHorizontal(orientation), handleWidth: !isHorizontal(orientation), onResize: actualizeSizes, refreshMode: "debounce", refreshRate: 50 }),
        react_1.default.createElement(react_resizable_panels_1.PanelGroup, { direction: isHorizontal(orientation) ? 'vertical' : 'horizontal' },
            react_1.default.createElement(react_resizable_panels_1.Panel, __assign({}, (primary === 'first' ? primaryPanelProps : secondaryPanelProps)), children[0]),
            react_1.default.createElement(react_resizable_panels_1.PanelResizeHandle, { className: (0, classnames_1.default)(styles.resizer, styles[orientation], (_b = {}, _b[styles.disabled] = !allowResize, _b)), disabled: !allowResize, hitAreaMargins: { coarse: 0, fine: 0 }, onDragging: handleDragging }),
            react_1.default.createElement(react_resizable_panels_1.Panel, __assign({}, (primary === 'second' ? primaryPanelProps : secondaryPanelProps)), children[1]))));
};
exports.ResizablePanes = ResizablePanes;
exports.ResizablePanes.displayName = 'ResizablePanes';
