let currentUsername = null;
let currentChannelId = null;

const configuration = {
    iceServers: [
        {
            urls: [
                "stun:stun1.l.google.com:19302",
                "stun:stun2.l.google.com:19302"
            ]
        }
    ],
    iceCandidatePoolSize: 10
};

window.setUsername = function (name) {
    currentUsername = name;
    LogMessage("Username set to: " + currentUsername);
};

window.setChannelId = function (channelId) {
    currentChannelId = channelId;
    LogMessage("Channel set to: " + currentChannelId);
};

function LogMessage(msg) {
    const messageLog = document.getElementById("messageLog");

    if (!messageLog) {
        console.log(msg);
        return;
    }

    messageLog.value += "\r\n" + msg;
    messageLog.scrollTop = messageLog.scrollHeight;
}

window.LogMessage = LogMessage;

window.addEventListener("HybridWebViewMessageReceived", function (e) {
    LogMessage("Raw message: " + e.detail.message);
});

window.addEventListener("load", async () => {
    LogMessage("RTC page loaded");

    window.HybridWebView.SendRawMessage("rtc_page_ready");

    Media.wireDeviceSelectors();
    await Media.loadDevices();
    await Media.ensureLocalMedia();
});

function testIndex(rawJson)
{
    const data = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
    if (data.sdp) {
        data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
    }
    handleRtcSignal(JSON.stringify(data));
    // if (data.type === "rtc_offer") {
    //     handleOffer(data)
    // }
    // if (data.type === "rtc_answer") {
    //     data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
    //     handleAnswer(data)
    // }
}

function noDataTest()
{
    LogMessage("No Data Called!!");
}