document.onkeydown = updateKey;
document.onkeyup = resetKey;

var server_port = 65432;
var server_addr = "192.168.31.81";   // the IP address of your Raspberry PI
const net = require('net');

// Function to request car status data
function get_car_status() {
    // const net = require('net');
    
    const client = net.createConnection({ port: server_port, host: server_addr }, () => {
        console.log('connected to server!');
        // Request status data
        client.write("GET_STATUS\r\n");
    });
    
    client.on('data', (data) => {
        try {
            const status = JSON.parse(data.toString());
            
            // Update UI elements with car status
            document.getElementById("direction").textContent = status.direction;
            document.getElementById("temperature").textContent = status.temperature + "°C";
            document.getElementById("speed").textContent = status.speed;
            document.getElementById("distance").textContent = status.distance_traveled.toFixed(2) + " m";
            
            // You could also update a small map visualization here
            
            console.log("Updated car status:", status);
        } catch (e) {
            console.error("Error parsing status data:", e);
        }
        
        client.end();
        client.destroy();
    });
    
    client.on('error', (err) => {
        console.error('Connection error:', err);
    });
}

function send_data(data) {
    // const net = require('net');
    
    const client = net.createConnection({ port: server_port, host: server_addr }, () => {
        console.log('connected to server!');
        // send the key code to the server
        client.write(`${data}\r\n`);
    });
    
    // get the response from the server
    client.on('data', (data) => {
        // Update the UI with any data received from the server
        // document.getElementById("direction").innerHTML = direction_dict[data];
        console.log(data.toString());
        client.end();
        client.destroy();
    });

    client.on('end', () => {
        console.log('disconnected from server');
    });
    
    client.on('error', (err) => {
        console.error('Connection error:', err);
    });
}

function client(){
    
    // const net = require('net');
    var input = document.getElementById("message").value;

    const client = net.createConnection({ port: server_port, host: server_addr }, () => {
        // 'connect' listener.
        console.log('connected to server!');
        // send the message
        client.write(`${input}\r\n`);
    });
    
    // get the data from the server
    client.on('data', (data) => {
        document.getElementById("bluetooth").innerHTML = data;
        console.log(data.toString());
        client.end();
        client.destroy();
    });

    client.on('end', () => {
        console.log('disconnected from server');
    });


}

// for detecting which key is been pressed w,a,s,d
function updateKey(e) {

    e = e || window.event;

    if (e.keyCode == '87') {
        // up (w)
        document.getElementById("upArrow").style.color = "green";
        send_data("87");
    }
    else if (e.keyCode == '83') {
        // down (s)
        document.getElementById("downArrow").style.color = "green";
        send_data("83");
    }
    else if (e.keyCode == '65') {
        // left (a)
        document.getElementById("leftArrow").style.color = "green";
        send_data("65");
    }
    else if (e.keyCode == '68') {
        // right (d)
        document.getElementById("rightArrow").style.color = "green";
        send_data("68");
    }
    else{
        send_data("0");
    }
}

// reset the key to the start state 
function resetKey(e) {

    e = e || window.event;
    send_data("0");
    document.getElementById("upArrow").style.color = "grey";
    document.getElementById("downArrow").style.color = "grey";
    document.getElementById("leftArrow").style.color = "grey";
    document.getElementById("rightArrow").style.color = "grey";
}


// update data for every 50ms
// function update_data(){
//     setInterval(function(){
//         // get image from python server
//         client();
//     }, 50);
// }

// Periodically update car status (every 1 second)
function update_data() {
    setInterval(function() {
        get_car_status();
    }, 1000);
}

// Call update_data when the page loads
window.onload = function() {
    update_data();
};