/*!
 * Custom elements for Nanopore-Digital Web applications
 */
'use strict';

/** Begins listening for dragging. */
function drag(container, options) {
    const initialOffsets = {
        pageX: 0,
        pageY: 0,
        offsetX: 0,
        offsetY: 0,
    };
    function move(pointerEvent) {
        const dims = container.getBoundingClientRect();
        const defaultView = container.ownerDocument.defaultView;
        const offsetX = dims.left + defaultView.pageXOffset;
        const offsetY = dims.top + defaultView.pageYOffset;
        let x = 0;
        let y = 0;
        if (options.relative) {
            x =
                pointerEvent.pageX -
                    initialOffsets.pageX -
                    (offsetX - initialOffsets.offsetX);
            y =
                pointerEvent.pageY -
                    initialOffsets.pageY -
                    (offsetY - initialOffsets.offsetY);
        }
        else {
            x = pointerEvent.pageX - offsetX;
            y = pointerEvent.pageY - offsetY;
        }
        if (options?.onMove) {
            options.onMove(x, y);
        }
    }
    function stop() {
        document.removeEventListener('pointermove', move);
        document.removeEventListener('pointerup', stop);
        if (options?.onStop) {
            options.onStop();
        }
    }
    document.addEventListener('pointermove', move, { passive: true });
    document.addEventListener('pointerup', stop);
    if (!options?.initialEvent)
        return;
    let initialEvent;
    if (options?.initialEvent['touches']) {
        initialEvent = {
            pageX: (options?.initialEvent).touches[0].pageX,
            pageY: (options?.initialEvent).touches[0].pageY,
        };
    }
    else {
        initialEvent = {
            pageX: (options?.initialEvent).pageX,
            pageY: (options?.initialEvent).pageY,
        };
    }
    const defaultView = container.ownerDocument.defaultView;
    const dims = container.getBoundingClientRect();
    initialOffsets.pageX = initialEvent.pageX;
    initialOffsets.pageY = initialEvent.pageY;
    initialOffsets.offsetX = dims.left + defaultView.pageXOffset;
    initialOffsets.offsetY = dims.top + defaultView.pageYOffset;
    // move(initialEvent);
}

exports.drag = drag;
