// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import { MINUTE } from "@luxonis/common-fe-utils";
import { uuidv7 } from "uuidv7";
const GET_APP_CONNECTION = () => ({ GetAppConnection: {} });
const GET_CONNECTION_REFRESH_INTERVAL = 5 * MINUTE;
export class WebRtcCommsProxy {
    automaticTokenRefresh;
    #commsChannel;
    #refreshIntervalId = null;
    constructor(commsChannel, automaticTokenRefresh) {
        this.automaticTokenRefresh = automaticTokenRefresh;
        this.#commsChannel = commsChannel;
        // TODO: Handle more states (disconnect..)
        this.#commsChannel.on("message:json", event => {
            this.#handleCommsMessages(event);
        });
        if (automaticTokenRefresh) {
            this.#startRefreshInterval();
        }
    }
    sendMessageToCommsChannel(message) {
        switch (message) {
            case "getConnection": {
                const message = GET_APP_CONNECTION();
                const webRtcMessage = JSON.stringify({
                    cid: uuidv7(),
                    data: message,
                });
                if (webRtcMessage) {
                    this.#commsChannel.sendMessage(webRtcMessage);
                }
                else {
                    console.error("Failed to serialize GetAppConnectionMessage");
                }
            }
        }
    }
    handleClose() {
        if (this.#refreshIntervalId) {
            clearInterval(this.#refreshIntervalId);
        }
    }
    #handleCommsMessages(message) {
        if (this.#isAppConnectionResponse(message)) {
            if (this.automaticTokenRefresh) {
                this.automaticTokenRefresh(message.data.Ok.GetAppConnection.token);
            }
            else {
                console.warn("Automatic token refresh is not enabled but received app connection response.");
            }
        }
        else {
            console.error("Comms Proxy received unsupported message - ", message);
        }
    }
    #isAppConnectionResponse(message) {
        return message.data.Ok.GetAppConnection !== undefined;
    }
    #startRefreshInterval() {
        this.#refreshIntervalId = setInterval(() => {
            this.sendMessageToCommsChannel("getConnection");
        }, GET_CONNECTION_REFRESH_INTERVAL);
    }
}
//# sourceMappingURL=comms-proxy.js.map