let port;
let reader;
const decoder = new TextDecoder("utf-8");
let readibleoutput = 0;
let booleanArray = [];
// Request a port and open a connection.
async function connect() {
    //vraag aan de browser om een serial port te selecteren
    port = await navigator.serial.requestPort();
    await port.open({ baudRate: 9600 });
    reader = port.readable.getReader();
    console.log("Port is open!");
    readLoop()
}

// Read data from serial port
async function readLoop() {
    let buffer = [];

    // loop until reader.cancel() is called
    while (true) {
        // Wait for data
        const { value, done } = await reader.read();


        for (let iByte = 0; iByte < value.length; iByte++) {
            let singleByte = value[iByte];
            //functie maken er van met boolean!!!
            if (singleByte != 10) {
                buffer.push(singleByte);
            }
            else {
                let sensorString = decoder.decode(new Uint8Array(buffer));
                //Put all data in a json Array and parse it to a boolean array
                try {
                    // Parse the incoming data as JSON
                    // "replace(/'/g, '\"')" replaces all single quotes with double quotes with use of regular expressions. So we can use Jsonparse to parse it into a booleanArray
                    let SerialArray = JSON.parse(sensorString.replace(/'/g, '"'));
                    // Ensure SerialArray is an array
                    if (Array.isArray(SerialArray)) {
                        //Convert the array of strings to a boolean array
                        //When a bit is 1 it becomes true, when a bit is 0 it becomes false
                        booleanArray = SerialArray.map(bit => bit == '1');
                        console.log(booleanArray);
                    } else {
                        console.error("Dit is geen Array");
                    }
                } catch (e) {
                    console.log("json niet geparserd");
                }
                Movementloop()
                buffer = [];
            }
            if (done) {
                console.log('[readLoop] DONE', done);
                reader.releaseLock();
                break;
            }
        }
    }
    
}
// Sluit de poort
async function disconnect() {
    await reader.cancel();
    await port.close();
    console.log("Port is closed!");
}
//--------------------Game--------------------

let playerPosX = 500;
let playerPosY = 300;
let bullets = [];
let playerSpeed = 5;
let radius = 40;
let hit = false;
let shot = true;
async function Movementloop() {
if (booleanArray[1]) {
    playerPosX += 2;}
if (booleanArray[3]) {
    playerPosX -= 2;}
if (booleanArray[2]) {
    playerPosY += 2;}
if (booleanArray[0]) {
    playerPosY -= 2;}
}
function keyPressed() {
    if (keyIsDown(LEFT_ARROW) && playerPosX > 0 + radius) {
        playerPosX -= playerSpeed;
    }
    if (keyIsDown(RIGHT_ARROW) && playerPosX < width - radius) {
        playerPosX += playerSpeed;
    }
    if (keyIsDown(UP_ARROW) && playerPosY > 0 + radius) {
        playerPosY -= playerSpeed;
    }
    if (keyIsDown(DOWN_ARROW) && playerPosY < height - radius) {
        playerPosY += playerSpeed;
    }
}


// the function setup() is called once when the page is loaded
function setup(){
    // create a canvas element and append it to the body
    createCanvas(1250, 600);    
    frameRate(244);
    // disable the outline of shapes
    //declare the bullet with its variables
    myBullet = new bullet(playerPosX, playerPosY, 10, 20);  

    noStroke();
}

// the function draw() is called every frame
function draw(){
    keyPressed()
    // clear the background with a transparent black color
    background(0,0,0,100);
    //draw the bullet
    myBullet.draw();
    //update de variabel playerPosX en playerPosY en de terugkomende variabelen hit en shot
    let { hit, shot } = myBullet.update(playerPosX, playerPosY);
    // draw a circle at the mouse position
    circle(playerPosX, playerPosY, radius);
    if (hit) {
        console.log("player hit");
    }
    if (!shot) {
        console.log("player shot");
    }

    
}
//test
//test2