const express = require("express");
const sockServer = require("./src/models/WebSocketModel.js");

let webserver = express();

webserver.use(express.json());

webserver.get("/", (_, res) => {
  res.sendFile("index.html", { root: `${__dirname}/public` });
});

webserver.get("/public_games", (_, res) => {
  let ids = sockServer.getGameIds();
  res.json({ ids: ids });
});

webserver.get("/join_game/:gameId/:gameType", (req, res) => {
  let { gameId, gameType } = req.params;
  if (gameType === "private") {
    if (!sockServer.hasGame(gameId)) {
      sockServer.createGame(gameId, gameType);
    } else {
      console.log("Game already exists");
      if (sockServer.games[gameId].type === "public") {
        // TODO: THIS IS A HACK
        return res.sendFile("public/index.html", { root: __dirname });
      }
    }
    return res.sendFile("public/game.html", { root: __dirname });
  }
  if (!sockServer.hasGame(gameId)) {
    return res.status(404).send();
  }
  console.log("Sending room", gameId);
  // could also use server-side rendering to create the HTML
  // that way, we could embed the room code
  // and existing chat messages in the generated HTML
  // but the client can also get the roomId from the URL
  // and use Ajax to request the messages on load
  res.sendFile("public/game.html", { root: __dirname });
});

webserver.get("/public/gameClient.js", (_, res) => {
  res.sendFile("gameClient.js", { root: `${__dirname}/public` });
});

webserver.listen(3000, () => console.log("Web server started."));

console.log("Server started.");

// Game loop

//setInterval(() => {
//	console.log('Broadcasting message to clients, connections.length: ', connections.length);
//	connections.forEach(connection => {
//		connection.send('Hello, world!')
//	})
//}, 1000);