"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyController = void 0;
const sync_store_1 = require("../../../util/events/sync-store");
class KeyPress {
    constructor(key, ts) {
        this.key = key;
        this.ts = ts;
    }
}
/**
 * Keeps track of all pressed down keys.
 */
class KeyController {
    constructor(dom) {
        this.dom = dom;
        /**
         * All currently pressed keys.
         */
        this.pressed = new Set();
        /**
         * History of last 5 pressed keys.
         */
        this.history = new sync_store_1.ValueSyncStore([]);
    }
    /** ----------------------------------------------------- {@link Printable} */
    start() {
        const onKeyDown = (event) => {
            const key = event.key;
            if (event.isComposing || key === 'Dead')
                return;
            const { pressed, history } = this;
            pressed.add(key);
            const press = new KeyPress(key, Date.now());
            const historyList = history.value;
            historyList.push(press);
            if (historyList.length > 5)
                historyList.shift();
            history.next(historyList, true);
        };
        const onKeyUp = (event) => {
            const key = event.key;
            if (event.isComposing || key === 'Dead')
                return;
            this.pressed.delete(key);
        };
        const onReset = () => {
            this.pressed.clear();
        };
        document.addEventListener('keydown', onKeyDown);
        document.addEventListener('keyup', onKeyUp);
        document.addEventListener('focus', onReset);
        document.addEventListener('compositionstart', onReset);
        document.addEventListener('compositionend', onReset);
        const el = this.dom.el;
        el.addEventListener('blur', onReset);
        return () => {
            document.removeEventListener('keydown', onKeyDown);
            document.removeEventListener('keyup', onKeyUp);
            document.removeEventListener('focus', onReset);
            document.removeEventListener('compositionstart', onReset);
            document.removeEventListener('compositionend', onReset);
            el.removeEventListener('blur', onReset);
        };
    }
    /** ----------------------------------------------------- {@link Printable} */
    toString(tab) {
        return `keys { hold: [ ${[...this.pressed].map((key) => JSON.stringify(key)).join(', ')}, hist: [ ${this.history.value.map((press) => JSON.stringify(press.key)).join(', ')} ] ] }`;
    }
}
exports.KeyController = KeyController;
//# sourceMappingURL=KeyController.js.map