import express from 'express';
import { Game } from './Game';
import WebSocket, { Server } from 'ws';
import { GameWebSocket } from './models/GameWebSocket';

const app = express();
const WebSocketServer = Server;
const port = process.env.PORT || 3000;

app.use(express.static('distClient/'));

const server = app.listen(port, () => {
  console.log(`Tron.io running on port ${port}`);
});

const wss = new WebSocketServer({ server });

const game = new Game();

wss.on('connection', function (connection: WebSocket) {
  connection.on('close', () => game.logout(connection as GameWebSocket));

  connection.on('message', ( message ) => {
    try {
      const data = JSON.parse(message as string);
      switch (data.type) {
        case 'login': game.login(connection as GameWebSocket, data.name); break;
        case 'respawn': game.respawn(connection as GameWebSocket); break;
        case 'update': game.update(connection as GameWebSocket, data.player); break;
      }
    } catch (e) {
      return
    }
  });
});
