import { AsyncDirective, directive, PartType } from 'lit/async-directive.js';
import { noChange, nothing } from 'lit';
class LongPressDirective extends AsyncDirective {
    constructor(part) {
        super(part);
        this.handlePointerDown = (event) => {
            if (event.button !== 0 || this.host.disabled) {
                return;
            }
            this.spinOnLongPressCallback(event);
        };
        this.handlePointerUp = (pointerUp) => {
            pointerUp?.preventDefault();
            pointerUp?.stopPropagation();
            if (this.timeout) {
                this.callbacks.start();
            }
            this.stopSpinningAndCleanUp();
            this.callbacks.end();
            document.removeEventListener('pointerup', this.handlePointerUp);
        };
        if (part.type !== PartType.ELEMENT || !(part.element instanceof HTMLButtonElement)) {
            throw new Error('The `longPress` directive must be used on an HTMLButtonElement.');
        }
    }
    render(_callback) {
        return nothing;
    }
    update(part, [callbacks]) {
        if (this.callbacks === undefined && this.host === undefined) {
            this.host = part.element;
            this.callbacks = { ...callbacks };
            this.host.addEventListener('pointerdown', this.handlePointerDown);
        }
        return noChange;
    }
    disconnected() {
        this.stopSpinningAndCleanUp();
        this.host.removeEventListener('pointerdown', this.handlePointerDown);
        document.removeEventListener('pointerup', this.handlePointerUp);
    }
    spinOnLongPressCallback(event) {
        event.preventDefault();
        event.stopPropagation();
        this.timeout = setTimeout(() => {
            this.timeout = undefined;
            this.interval = setInterval(() => {
                this.callbacks.start();
            }, 50);
        }, 500);
        document.addEventListener('pointerup', this.handlePointerUp);
        this.observer?.disconnect();
        this.observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.attributeName === 'disabled') {
                    this.stopSpinningAndCleanUp();
                }
            });
        });
        this.observer.observe(this.host, { attributes: true });
    }
    stopSpinningAndCleanUp() {
        clearInterval(this.interval);
        clearTimeout(this.timeout);
        this.observer?.disconnect();
    }
}
export const longPress = directive(LongPressDirective);
