
//////////////////
/// Status streams
//////////////////


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

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

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

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


////////////////////
/// Telescope stream
////////////////////

socket.on("/api/telescope/status",function(e) {
    var res = e //JSON.parse(e.data)
    // console.log(res)
    $.each(res, function(k,v){
        var elem = $("[data-status=telescope-"+k)
        if (elem) {
            //console.log(k)
            elem.text(v.response)
        }
    })

    if (res && res.coordinates) {
        $("[data-status=telescope-coordinates-ra").text(res.coordinates.response.radec[0])
        $("[data-status=telescope-coordinates-dec").text(res.coordinates.response.radec[1])
        $("[data-status=telescope-coordinates-alt").text(res.coordinates.response.altaz[0].toFixed(3))
        $("[data-status=telescope-coordinates-az").text(res.coordinates.response.altaz[1].toFixed(3))
        $("[data-status=telescope-coordinates-ha").text(res.coordinates.response.ha)
        $("[data-status=telescope-coordinates-lst").text(res.coordinates.response.lst)
    }

    if (res && res.offset) {
        $("[data-status=telescope-offset-zd").text((res.offset.response[0]*3600).toFixed(1))
        $("[data-status=telescope-offset-az").text((res.offset.response[1]*3600).toFixed(1))
    }

    if (res && res.rotator) {
        $("[data-status=telescope-offset-rot").text(res.rotator.response.toFixed(1))
    }
});

//////////////////
/// Dome stream
//////////////////

socket.on("/api/dome/status",function(e) {
    var res = e //JSON.parse(e.data)
    // console.log(res)

    $.each(res, function(k,v){
        var elem = $("[data-status=dome-"+k)
            if (elem) {
                elem.text(v.response)
            }
    });

    if (res && res.position) {
        $("[data-status=dome-azimuth").text(res.position.response.azimuth)
        $("[data-status=dome-parked").text(res.position.response.parked)
    }

});

//////////////////
/// Camera stream
//////////////////

socket.on("/api/camera/status",function(e) {
    var res = e //JSON.parse(e.data)
    // console.log(res)

    $.each(res, function(k,v){
        var elem = $("[data-status=camera-"+k)
        if (elem) {
            elem.text(v.response)
        }
    });

    if (res && res.settings) {
        $.each(res.settings, function(k,v){
            var elem = $("[data-status=camera-"+k)
            if (elem) {
                elem.text(v.response)
            }
        });
    }

});

/////////////////////
/// Sequencer stream
/////////////////////

socket.on("/api/sequencer/run",function(e) {
    var res = e //JSON.parse(e.data)
    
    $.each(res.response, function(k,v){ /// sequencer has just 1 response
        var elem = $("[data-status=sequencer-"+k)
            if (elem) {
                elem.text(v)
            }
    });

    /// For the JS9 display
    var auto_display = $("#auto-display").prop("checked")
    if (auto_display) {
        if (typeof JS9 != "undefined") {
            JS9.Load("/static/temp.fits", {refresh:true, colormap:"heat"} )

        }
    }

    /// For the d3.js focus output
    var auto_output = $("#auto-output").prop("checked")
    if (auto_output) {
        if (res.response.output && res.response.output.focus) {            
            const focus = res.response.output.focus
            const data = focus.m2.map((x, i) => ({ x, y: focus.fwhm[i] }));
            if (typeof chart1 != "undefined") {        
                chart1.update(data);
            }
        }
    }

});

///////////////////////
/// Environment stream
///////////////////////

socket.on("/api/environment/status", function(e) {
    var res = e //JSON.parse(e.data)
    // console.log(res)

    if (res && res.external) {
        $.each(res.external, function(k,v){
            var elem = $("[data-status=environment-external-"+k)
            if (elem) {
                elem.text(v)
            }
        });
    }

    if (res && res.internal) {
        $.each(res.internal, function(k,v){
            var elem = $("[data-status=environment-internal-"+k)
            if (elem) {
                elem.text(v)
            }
        });
    }

});

///////////////////////
/// Webcam stream
///////////////////////

socket.on("/api/webcam/snapshot", function(e) {
    var res = e //JSON.parse(e.data)
    const elem = $("[data-status=webcam-snapshot")
    //console.log(res)

    if (res) {
        const url = btoa(String.fromCharCode(...new Uint8Array(res)));
        elem.attr("src", 'data:image/jpeg;base64,' + url)
    } else {
        console.log("no image?")
    }

});


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

var ansi_up = new AnsiUp;
socket.on("new_lines", function(lines) {    
    
    var log_level_list = ["DEBUG", "INFO", "WARNING", "ERROR"];
    var log_level = "";
    $.each(log_level_list, function(index, value) {
        if (lines.indexOf(value) !== -1) {
            log_level = value+'-level-line';
            return false;
        }
    });
    
    lines.forEach(function(line){        
        $("#stream-output").prepend(
            '<div class="'+log_level+'">'+ansi_up.ansi_to_html(line)+'</div>'
        );
    })
        
});
