const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

const connections = new Set();
var playerCount = 0;
var players = []

app.get('/', (req, res) => {
  res.send('Grand Tabernacle Auto VI');
});

players.push({
    id: playerCount,
    x: 100,
    y: 100,
    dir: 4,
    visibleDir: 4,
    name: playerCount.toString() + "joueur"
  })
playerCount++;

function createNewPlayer(socket){
  var obj = {
    id: playerCount,
    x: Math.floor(Math.random()*1000),
    y: Math.floor(Math.random()*1000),
    dir: 0,
    visibleDir: 0,
    name: playerCount.toString() + "joueur"
  }
  players.push(obj);
  playerCount++;

  socket.send(JSON.stringify({
    type: "connect",
    data: {
      playerId: obj.id,
      players: players
    }
  }))

  broadcast(JSON.stringify({
    type: "newplayer",
    data: obj
  }), obj.id);

  socket.id = obj.id;
  connections.add(socket);
}

wss.on('connection', (socket) => {
  //create new player, send informations to new player and broadcast new player for all
  createNewPlayer(socket);

  socket.on('message', (message) => {
    message = JSON.parse(message);
    if (message.type == "ping") {
      socket.send("pong");
    } else if(message.type=="update") {
      broadcast(JSON.stringify(message), socket.id);
    }
  });

  socket.on('close', () => {
    for (var i = players.length - 1; i >= 0; i--) {
      if(players[i].id==socket.id){
        players.splice(i, 1);
      }
    }
    connections.delete(socket);
  });
});

function broadcast(message, exceptId = -1) {
  connections.forEach((socket) => {
    if (socket.readyState === WebSocket.OPEN && socket.id!=exceptId) {
      socket.send(message);
    }
  });
}

const PORT = 8080;

server.listen(PORT, () => {
  console.log(`Serveur WebSocket écoutant sur le port ${PORT}`);
});
