import { Server } from "http";
import { Server as ServerIO } from "socket.io";
import { CORS_ORIGIN } from "./constants";

type DataInterface = {
  message?: string;
  pathname?: string;
  username?: string;
};

// Initially we have zero users
const users: { [key: string]: DataInterface } = {};

export default (http: Server): ServerIO => {
  const io = new ServerIO(http, { cors: { origin: CORS_ORIGIN } });

  // socket.io connection
  io.on("connection", (socket) => {
    console.log(`${socket.id} user just connected!`);

    // Listens when a new user joins the server
    socket.on("newUser", (data: DataInterface) => {
      // Adds the new user to the list of users
      console.log(`New user from ${socket.id}`);
      console.log(data);
      users[socket.id] = data;
      io.emit("listUsers", users);
    });

    // Listens when a user sends a message
    socket.on("message", (data: DataInterface) => {
      console.log(`Message from ${socket.id} (${data.username})`);
      console.log(data);
      io.emit("message", data);
    });

    // Listen when a user is writing
    socket.on("startWriting", (data: DataInterface) => {
      console.log(`Start Writing from ${socket.id} (${data.username})`);
      console.log(data);
      io.emit("startWriting", data);
    });

    // Listen when a user is writing
    socket.on("stopWriting", (data: DataInterface) => {
      console.log(`Stop Writing from ${socket.id} (${data.username})`);
      console.log(data);
      io.emit("stopWriting", data);
    });

    socket.on("disconnect", () => {
      console.log(`${socket.id} disconnect.`);
      if (socket.id in users) delete users[socket.id];
      io.emit("listUsers", users);
      socket.disconnect();
    });
  });

  return io;
};
