import { RouterClient } from "../../clients/routerClient";
import * as Constants from "../constants";
class FinsembleEvent {
    constructor(params, queryMessage) {
        var _a;
        this.allowDelay = false;
        this.delayed = false;
        this.allowCancel = false;
        this.canceled = false;
        this.completed = false;
        this.event = params.event;
        this.source = params.source;
        this.sourceType = params.sourceType;
        this.listenerGuid = params.listenerGuid;
        if (Constants[this.sourceType.toUpperCase()] &&
            Constants[this.sourceType.toUpperCase()].DELAYABLE_EVENTS.includes(this.event)) {
            this.allowDelay = true;
        }
        if (Constants[this.sourceType.toUpperCase()] &&
            Constants[this.sourceType.toUpperCase()].CANCELABLE_EVENTS.includes(this.event)) {
            this.allowCancel = true;
        }
        this.handler = params.handler;
        this.queryMessage = queryMessage;
        this.guid = (_a = queryMessage === null || queryMessage === void 0 ? void 0 : queryMessage.data) === null || _a === void 0 ? void 0 : _a.guid;
        this.internalHandler();
    }
    async internalHandler() {
        var _a, _b;
        this.data = (_b = (_a = this.queryMessage) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data;
        if (this.handler)
            await this.handler(this);
        if (!(this.delayed || this.canceled || this.completed)) {
            this.done();
        }
    }
    cancel() {
        if (this.allowCancel) {
            this.canceled = true;
            this.done();
        }
    }
    wait() {
        var _a;
        if (this.allowDelay) {
            this.delayed = true;
            (_a = this.queryMessage) === null || _a === void 0 ? void 0 : _a.sendQueryResponse(null, { wait: true });
        }
        else {
            this.done();
        }
    }
    done(data) {
        var _a;
        this.completed = true;
        // If the listener caused a delay, it cannot send a queryResponse again, so it must transmit.
        if (this.delayed) {
            RouterClient.transmit(`Finsemble.Listener.Done.${this.guid}.${this.listenerGuid}`, {
                canceled: this.canceled,
                data,
            });
        }
        else {
            (_a = this.queryMessage) === null || _a === void 0 ? void 0 : _a.sendQueryResponse(null, {
                canceled: this.canceled,
                data,
            });
        }
    }
}
export default FinsembleEvent;
//# sourceMappingURL=FinsembleEvent.js.map