const currentUrl = window.location.href;
var counter = 0;
var socket = null;

function executeFunction(key, ...args) {
    if (functionMap.has(key)) {
        const func = functionMap.get(key);
        func(...args);
    } else {
        console.log(`No function found for key: ${key}`);
    }
}

function sendInfo(socket) {
    console.log('current URL:', currentUrl);

    // 2. Creating a URL object
    const url = new URL(currentUrl);

    // 3. Use of URLSearchParams to read the parameters
    const params = new URLSearchParams(url.search);

    // 4. Retrieve a specific parameter (e.g. 'id')
    const applicationId = params.get('applicationId');
    console.log('Parameter "applicationId":', applicationId);
    const sessionToken = params.get('sessionToken');
    console.log('Parameter "sessionToken":', sessionToken);

    let message = {
        cmd: "info",
        applicationId: applicationId == null ? "" : applicationId,
        sessionToken: sessionToken == null ? "" : sessionToken,
    }

    sendMessage(socket, message);
}

/*window.addEventListener('beforeunload', (event) => {
    event.preventDefault();
    event.returnValue = '';
});*/

document.addEventListener('DOMContentLoaded', () => {
    if ((socket === null || socket.readyState === WebSocket.CLOSED) && counter === 0) {
        // get url
        const url = getWebSocketUrl();
        counter++;

        // open web socket connection
        socket = new WebSocket(url);

        socket.onopen = function (event) {
            console.log('WebSocket connection opened:', event);
            sendInfo(socket);
        };

        socket.onmessage = function (event) {
            console.log('Got message:', event.data);

            // Receive and parse JSON data
            const data = JSON.parse(event.data);

            const cmd = data.cmd;
            console.log(cmd);

            switch (cmd) {
                case 'setInnerHtml': {
                    const id = data.id;
                    const html = data.html==null ? "" : data.html;
                    executeFunction(cmd, socket, id, html);
                    break;
                }
                case 'addStyleSheet': {
                    const id = data.id;
                    const content = data.content;
                    executeFunction(cmd, socket, id, content);
                    break;
                }
                case 'removeStyleSheet': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                case 'addScript': {
                    const id = data.id;
                    const content = data.content;
                    const src = data.src;
                    const onLoad = data.onLoad;
                    executeFunction(cmd, socket, id, content, src, onLoad);
                    break;
                }
                case 'removeScript': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                case 'listenOnClick1': {
                    const id = data.id;
                    const widgetIds = data.widgetIds;
                    executeFunction(cmd, socket, id, widgetIds);
                    break;
                }
                case 'listenOnClick2': {
                    const widgetIds = data.ids;
                    executeFunction(cmd, socket, widgetIds);
                    break;
                }
                case 'openNewTab': {
                    const sameUrl = data.sameUrl;
                    const url = data.url;
                    const parameters = new Map(Object.entries(data.parameters));
                    console.log(parameters);
                    executeFunction(cmd, socket, sameUrl, url, parameters);
                    break;
                }
                case 'addTableRowEventListener': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                // TODO create message
                case 'addListRowEventListener': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                case 'addElementClasses': {
                    const selector = data.selector;
                    const classes = data.classes;
                    executeFunction(cmd, socket, selector, classes);
                    break;
                }
                case 'removeElementClasses': {
                    const selector = data.selector;
                    const classes = data.classes;
                    executeFunction(cmd, socket, selector, classes);
                    break;
                }
                case 'showModal': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                case 'showModal2': {
                    const html = data.html;
                    executeFunction(cmd, socket, html);
                    break;
                }
                case 'setValue': {
                    const id = data.id;
                    const value = data.value==null ? "" : data.value;
                    executeFunction(cmd, socket, id, value);
                    break;
                }
                case 'removeElement': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                case 'uikitAlert': {
                    const message = data.message;
                    const options = data.options;
                    executeFunction(cmd, socket, message, options);
                    break;
                }
                case 'alert': {
                    const message = data.message;
                    executeFunction(cmd, socket, message);
                    break;
                }
                case 'setStylesForElements': {
                    const selector = data.selector;
                    const styles = new Map(Object.entries(data.styles));
                    executeFunction(cmd, socket, selector, styles);
                    break;
                }
                case 'setImage': {
                    const id = data.id;
                    const src = data.src;
                    executeFunction(cmd, socket, id, src);
                    break;
                }
                case 'setFocus': {
                    const id = data.id;
                    executeFunction(cmd, socket, id);
                    break;
                }
                default: {
                    console.log('unknown message');
                    break;
                }
            }
        }

        socket.onerror = function (error) {
            console.error('WebSocket error: ', error);
        };

        socket.onclose = function (event) {
            console.log('WebSocket connection closed: ', event);
        };
    }
});

function getWebSocketUrl() {
    const protocol = window.location.protocol;
    const hostname = window.location.hostname;

    // Set the WebSocket protocol based on the current protocol
    let wsProtocol;
    if (protocol === 'https:') {
        wsProtocol = 'wss:';
    } else {
        wsProtocol = 'ws:';
    }

    // Building the WebSocket URL with port 8087
    const wsPort = 8087;
    return `${wsProtocol}//${hostname}:${wsPort}`;

}

linkClick = function (id) {
    executeFunction("linkClick", socket, id);
}
window.linkClick = linkClick;