"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyboardInputEntity = void 0;
exports.makeKeyboardInput = makeKeyboardInput;
const core_1 = require("@vived/core");
const core_2 = require("@vived/core");
class KeyboardInputEntity extends core_2.AppObjectEntity {
}
exports.KeyboardInputEntity = KeyboardInputEntity;
KeyboardInputEntity.type = "KeyboardInputEntity";
KeyboardInputEntity.get = (appObjects) => (0, core_1.getSingletonComponent)(KeyboardInputEntity.type, appObjects);
function makeKeyboardInput(appObject) {
    return new KeyboardInputImp(appObject);
}
class KeyboardInputImp extends KeyboardInputEntity {
    get eventElement() {
        return this._eventElement;
    }
    constructor(appObject) {
        super(appObject, KeyboardInputEntity.type);
        this.controllers = [];
        this._eventElement = undefined;
        this._pressedKeyCodes = [];
        this.setEventElement = (element) => {
            this.clearInputElement();
            element.addEventListener("keydown", this.submitKeyDown, false);
            element.addEventListener("keyup", this.submitKeyUp, false);
            this._eventElement = element;
        };
        this.clearInputElement = () => {
            if (!this._eventElement)
                return;
            this._eventElement.removeEventListener("keydown", this.submitKeyDown);
            this._eventElement.removeEventListener("keyup", this.submitKeyUp);
            this._eventElement = undefined;
        };
        this.submitKeyDown = (e) => {
            this._pressedKeyCodes.push(e.code);
            this.controllers.forEach((c) => {
                if (c.onKeyDown) {
                    c.onKeyDown(e);
                }
            });
        };
        this.submitKeyUp = (e) => {
            this._pressedKeyCodes = this._pressedKeyCodes.filter((keyCode) => {
                if (keyCode === e.code) {
                    return false;
                }
                return true;
            });
            this.controllers.forEach((c) => {
                if (c.onKeyUp) {
                    c.onKeyUp(e);
                }
            });
        };
        this.registerController = (controller) => {
            this.controllers.push(controller);
        };
        this.removeController = (controller) => {
            const index = this.controllers.indexOf(controller);
            if (index >= 0) {
                this.controllers.splice(index, 1);
            }
        };
        this.isKeyPressed = (keyCode) => {
            for (const code of this._pressedKeyCodes) {
                if (code === keyCode) {
                    return true;
                }
            }
            return false;
        };
    }
}
//# sourceMappingURL=KeyboardInput.js.map