import { createServer } from "http";
import next from "next";
import { Server } from "socket.io";
import { Clients } from "./clients.js";

const port = 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handler = app.getRequestHandler();
const clients = new Clients();

app.prepare().then(() => {
  const httpServer = createServer(handler);

  const io = new Server(httpServer, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
    addTrailingSlash: false,
    transports: ["websocket", "polling"],
  });

  io.on("connection", (socket) => {
    clients.addSocket(socket.id, socket);

    // on new connection
    socket.emit("admin-getvisitor", { visitor: clients.listData() });

    socket.on("update-visitor", (data) => {
      clients.updateData(socket.id, data);
      clients.broadcast("admin-getvisitor", { visitor: clients.listData() });
    });

    socket.on("admin-getvisitor", () => {
      socket.emit("admin-getvisitor", { visitor: clients.listData() });
    });

    socket.on("disconnect", () => {
      clients.removeSocket(socket.id);
      clients.broadcast("admin-getvisitor", { visitor: clients.listData() });
    });
  });

  httpServer
    .once("error", (err) => {
      console.error(err);
      process.exit(1);
    })
    .listen(port, () => {
      console.log(`> Ready Next.js with Socket.IO`);
    });
});
