// /AIWK_COMMON/win/aiwk_win_drag.js
// AIWK EXT4 v028
(function () {
    "use strict";

    const AIWK = window.AIWK;

    AIWK.winDrag = {
        attach: function (win) {
            let active = false;
            let sx = 0;
            let sy = 0;
            let ox = 0;
            let oy = 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-moving");
                try {
                    ev.currentTarget.releasePointerCapture(ev.pointerId);
                } catch (err) {
                }
                win.saveRect();
                stop(ev);
            }

            function start(ev) {
                if (ev.button !== 0) {
                    return;
                }
                active = true;
                sx = ev.clientX;
                sy = ev.clientY;
                ox = parseInt(win.el.style.left || "0", 10);
                oy = parseInt(win.el.style.top || "0", 10);
                win.bringFront();
                ev.currentTarget.setPointerCapture(ev.pointerId);
                win.el.classList.add("aiwk-moving");
                win.showRectStatus("status.moving", "moving");
                stop(ev);
            }

            function move(ev) {
                if (!active) {
                    return;
                }
                win.setRect({
                    x: ox + ev.clientX - sx,
                    y: oy + ev.clientY - sy
                });
                win.showRectStatus("status.moving", "moving");
                stop(ev);
            }

            [win.parts.handle, win.parts.bottomDrag].forEach(function (dragHandle) {
                if (!dragHandle) {
                    return;
                }
                dragHandle.addEventListener("pointerdown", start);
                dragHandle.addEventListener("pointermove", move);
                dragHandle.addEventListener("pointerup", end);
                dragHandle.addEventListener("pointercancel", end);
            });
        }
    };
}());
