$(document).ready(function () {
    // Your code here
    //console.log('precordedbroadcast.js is ready!');
    const path = window.location.pathname;
    const ws = new WebSocket('ws://' + window.location.host + path + '/ws');
    for (let i = 1; i <= 8; i++) {
        $(`#fileM${i}`).val('');
        $(`#playM${i}`).prop('disabled', true);
        $(`#stopM${i}`).prop('disabled', true);
    }

    ws.onopen = function () {
        //console.log('WebSocket connection opened');
        $('#indicatorDisconnected').addClass('visually-hidden');
        $('#indicatorConnected').removeClass('visually-hidden');

        sendCommand({ command: "getMessageConfig" });
        setInterval(function () {
            sendCommand({ command: "getPlaybackStatus" });
        }, 1000); // every second
    };

    ws.onmessage = function (event) {
        //console.log('WebSocket message received:', event.data);
        let msg = {};
        try {
            msg = JSON.parse(event.data);
        } catch (e) {
            return;
        }

        if (msg.reply && msg.reply.length > 0 && msg.data && msg.data.length > 0) {
            switch (msg.reply) {
                case "playMessage":
                    if (msg.data !== "success") 
                        {alert(msg.data);}
                    else{
                        $('#playbackStatus').text('Playback started');
                    }
                    break;
                case "stopMessage":
                    if (msg.data !== "success") 
                        {alert(msg.data);}
                    else{
                        $('#playbackStatus').text('Playback stopped');
                    }
                    break;
                case "getMessageConfig":
                    const messageConfigdata = JSON.parse(msg.data);
                    //console.log('Message Config Data:', messageConfigdata);
                    for (let i = 1; i <= 8; i++) {
                        let filetitle = $(`#fileM${i}`);
                        let playButton = $(`#playM${i}`);
                        let stopButton = $(`#stopM${i}`);
                        let fileInput = messageConfigdata[`M${i}`];
                        if (fileInput && fileInput.length > 0) {
                            filetitle.text(fileInput);
                            playButton.prop('disabled', false);
                            stopButton.prop('disabled', false);
                            playButton.removeClass('invisible');
                            stopButton.removeClass('invisible');
                            playButton.on('click', function () {
                                let cmd = {
                                    command: "playMessage",
                                    data: `M${i}`
                                }

                                sendCommand(cmd);
                            });
                            stopButton.on('click', function () {
                                let cmd = {
                                    command: "stopMessage",
                                    data: `M${i}`
                                }
                                sendCommand(cmd);
                            });
                        } else {
                            filetitle.text('Not configured');
                            playButton.addClass('invisible');
                            stopButton.addClass('invisible');

                        }


                    }
                    break;
                case "getPlaybackStatus":
                    $('#playbackStatus').text(msg.data);
                    break;
            }
        }



    };

    ws.onclose = function () {
        //console.log('WebSocket connection closed');
        $('#indicatorDisconnected').removeClass('visually-hidden');
        $('#indicatorConnected').addClass('visually-hidden');
    };

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

    function sendCommand(cmd) {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(cmd));
        } else {
            console.error('WebSocket is not open. Unable to send command:', JSON.stringify(cmd));
        }
    }
});