"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InProcessTransportSession = exports.InProcessTransport = void 0;
const transport_1 = require("./transport");
/**
 * Implements an {@link ITransport} for in-process use (does not support inter-process communication) with support for multiple
 * apps within the current process.
 */
class InProcessTransport {
    constructor(deser) {
        this.deser = deser;
        this.clients = new Map();
    }
    async connect(appId, onMessage) {
        this.clients.set(appId, {
            appId,
            onMessage
        });
        return new InProcessTransportSession(this.clients, this.deser, appId);
    }
}
exports.InProcessTransport = InProcessTransport;
class InProcessTransportSession {
    constructor(clients, deser, appId) {
        this.appId = appId;
        this.clients = clients;
        this.deser = deser;
    }
    async send(envelope, contents, failure) {
        const client = this.clients.get(envelope.receiverId);
        if (client) {
            try {
                const c = contents === undefined ? undefined : this.deser.deserialize(this.deser.serialize(contents));
                const f = failure === undefined ? undefined : this.deser.deserialize(this.deser.serialize(failure));
                client.onMessage(envelope, c, f);
                return;
            }
            catch (e) {
                console.log(e); // TODO
            }
        }
        else {
            this.sendFailureMessage(envelope, transport_1.TRANSPORT_ERROR_UNKNOWN_RECEIVER, `Receiver [${envelope.receiverId}] is not registered to the in-process transport (only ${JSON.stringify(Array.from(this.clients.keys()))} is/are registered)`);
        }
    }
    async finalize() {
        this.clients.delete(this.appId);
    }
    sendFailureMessage(originalEnv, code, msg) {
        const failure = {
            code,
            message: msg
        };
        if (originalEnv.returnEnvelopes) {
            for (const env of originalEnv.returnEnvelopes) {
                this.send(env, undefined, failure);
            }
        }
    }
}
exports.InProcessTransportSession = InProcessTransportSession;
