const WebSocket = require('ws');
const express = require('express')
const http = express()
const config = require("./settings.json");
const httpPort = config.httpPort
const appPort = config.appPort

var board = new Array(config.boardHeight * config.boardWidth * 4);
board.fill(127);

const server = new WebSocket.Server({
  port: appPort
});

let clients = [];

const evaulatePixelNumber = (x, y) => {   
    let pixelNumber;
    if (y > 0)
        pixelNumber = (y) * config.boardWidth + x
    if (y == 0)
        pixelNumber = x
    return pixelNumber
}

server.on('connection', function(client) {
    clients.push(client);

  // When you receive a message, send that message to every socket.
  client.on('message', function(msg) {
    let packet;
    try {
        packet = JSON.parse(msg.toString());
        content = packet.content
        code = packet.code
    } catch (e) {console.log(e)}
    let response = {};
    switch(code) {
        case 0:
            response.code = 0;
            response.content = board;
            console.log(Buffer.from(JSON.stringify(response)))
            client.send(Buffer.from(JSON.stringify(response)));
        break;
        case 1:
            response.code = 1;
            response.content = content;
            console.log(`response content ${response.content}`)
            contentJson = JSON.parse(content);
            let pixelNumber = evaulatePixelNumber(contentJson.x, contentJson.y)
            if (contentJson.x < 0 || contentJson.y < 0) {
                break;
            }
            board[pixelNumber + 0] = contentJson.r
            board[pixelNumber + 1] = contentJson.g
            board[pixelNumber + 2] = contentJson.b
            board[pixelNumber + 3] = 255
            clients.forEach(c => c.send(Buffer.from(JSON.stringify(response))));
        break;
        default:
            console.log("Packet cannot be understood: ", packet);
            client.send("{\"code\":-1}")
    }
    // clients.forEach(s => s.send(msg));
  });

  // When a socket closes, or disconnects, remove it from the array.
  client.on('close', function() {
    clients = clients.filter(s => s !== client);
  });
});

http.get('/', (req, res) => {
    res.sendFile('html/index.html', {root: __dirname })
})
  
http.listen(httpPort, () => {
    console.log(`Starting pixelbattle http server on port ${httpPort}`)
})
