//////////////////
/// Connection
//////////////////

var socket = io.connect({
    //transports: ['websocket'],
    transports: ['polling'],
    path: "/web/socket",
});

socket.on('connect', function() {
    console.log('Connected to server');

});

socket.on('disconnect', function() {
    console.log('Disconnected from server');
});

socket.on('error', function(e) {
    console.log(e);
});

socket.on('timestamp', function(server_unix_time) {
    //console.log(server_unix_time)
    var diff = difftime(server_unix_time)
    $('[data-status=timestamp-diff]').text(diff)
    //console.log(diff)
});


// try {
//     parsedJson = JSON.parse(new TextDecoder().decode(matrix));
//     console.log(parsedJson);
// } catch (e) {
//     console.log(matrix);
// }



///////////////////////
/// Logfile stream
///////////////////////

var ansi_up = new AnsiUp;
socket.on("new-lines", function(lines) {
    //console.log(lines)
    lines.forEach(function(line){        
        $("#stream-output").prepend(
            '<div>'+ansi_up.ansi_to_html(line)+'</div>'
        );        
    })
});

//////////////////
/// RTC status
//////////////////

socket.on("rtc-status", function(data) {
    
    $('[data-status="ref_cx"]').text(data.cred.cx.toFixed(2))
    $('[data-status="ref_cy"]').text(data.cred.cy.toFixed(2))
    
    $('[data-status="current_cx"]').text(data.cloud.cx.toFixed(2))
    $('[data-status="current_cy"]').text(data.cloud.cy.toFixed(2))
    
    $("#image-skp_cmd-dm").text(data.dm.skp_cmd)
    $("#image-cloud_samples-cloud").text(data.cloud.cloud_samples)
    
    // console.log(data.cred.data[40])
    
    /// In drawings.js
    draw_image(data.cred, "cred") // cred image
    draw_image(data.gain, "cred", true ) // mask true
    draw_centroid(data.cred, "cred", "red") // red dot
    draw_circle(data.cloud, "cred", "red", 1) // red circle

    draw_dm(data.dm, "dm", false)
    draw_dm(data.dm, "dm2", true)
    
    draw_image(data.cloud, "cloud")
    
    /// Draw a circle corresponding to the center of rotation.
    /// "data" is a dummy array.
    /// "cx" and "cy" are the normalized coordinates
    
    //var center_of_rotation = {data:[1,2,3], cx:+0.28, cy:-0.11}
    var center_of_rotation = {data:[1,2,3], cx:+0.16, cy:+0.04}
    draw_circle(center_of_rotation, "cred", "white", 0.2) // red circle
    
});

////////////////////
/// JSON status
////////////////////

socket.on("json-status", function(data) {
    
    /// General
    $.each(data, function(key,status){
        $('[data-status="'+key+'"]').text(status.value)
    });

    /// devices part (devices.js)
    update_devices(data)
    
    /// SYNOPTIC part (synoptic.js)
    update_synoptic(data)
    
});

///////////////////////
/// Pulse on changes
///////////////////////

function pulse(selector) {

    // var done = "bg-success"
    // var delay = 200

    selector.fadeTo('slow', 0.5, function() {
      selector.fadeTo('slow', 1.0) //.removeClass(done);
    });

    // setTimeout(function() {
    //   selector.removeClass(done);
    // }, delay);

}

$(document).ready(function(){
    // Select all elements with data-status attribute
    const elements = document.querySelectorAll('[data-status]');

    // Object to store previous text content of each element
    const previousTextContent = {};

    // Function to monitor text changes
    function observeChanges(element) {
        const observer = new MutationObserver(mutationsList => {
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    const previousText = previousTextContent[element.getAttribute('data-status')];
                    const currentText = element.textContent.trim();
                    if (previousText !== currentText) {
                        pulse($(element))
                        previousTextContent[element.getAttribute('data-status')] = currentText;
                    }
                }
            }
        });
        
        observer.observe(element, { subtree: true, childList: true });
    }
    
    // Apply observeChanges function to each element
    elements.forEach(element => {
        previousTextContent[element.getAttribute('data-status')] = element.textContent.trim();
        observeChanges(element);
    });
    
});
