// /AIWK_COMMON/win/aiwk_win_resize.js
// AIWK EXT4 v004
(function () {
    "use strict";

    const AIWK = window.AIWK;

    AIWK.winResize = {
        attach: function (win) {
            let active = false;
            let sx = 0;
            let sy = 0;
            let ow = 0;
            let oh = 0;

            function stop(ev) {
                if (ev && ev.cancelable) {
                    ev.preventDefault();
                }
                if (ev) {
                    ev.stopPropagation();
                }
            }

            function end(ev) {
                if (!active) {
                    return;
                }
                active = false;
                win.el.classList.remove("aiwk-resizing");
                try {
                    win.parts.resize.releasePointerCapture(ev.pointerId);
                } catch (err) {
                }
                win.saveRect();
                stop(ev);
            }

            win.parts.resize.addEventListener("pointerdown", function (ev) {
                if (ev.button !== 0 || (win.collapseLevel || win.rect.collapsed)) {
                    return;
                }
                active = true;
                sx = ev.clientX;
                sy = ev.clientY;
                ow = parseInt(win.el.style.width || "420", 10);
                oh = parseInt(win.el.style.height || "260", 10);
                win.bringFront();
                win.parts.resize.setPointerCapture(ev.pointerId);
                win.el.classList.add("aiwk-resizing");
                win.showRectStatus("status.resizing", "resizing");
                stop(ev);
            });

            win.parts.resize.addEventListener("pointermove", function (ev) {
                if (!active) {
                    return;
                }
                const nextW = Math.max(260, ow + ev.clientX - sx);
                const nextH = Math.max(120, oh + ev.clientY - sy);
                win.setRect({
                    w: nextW,
                    h: nextH
                });
                win.showRectStatus("status.resizing", "resizing");
                stop(ev);
            });

            win.parts.resize.addEventListener("pointerup", end);
            win.parts.resize.addEventListener("pointercancel", end);
        }
    };
}());
