import { Server as Skio } from "socket.io";
import evt from "./events.js";
import modes from "./modes.js";

import { initiator, executor, viewer } from "./modifiers.js";

const socketDrop = (io, room, id) => {
  const { rooms } = io.of("/").adapter;
  const clients = rooms.get(room);
  if (clients.size > 1 || clients.size === 0) return;
  const socketId = Array.from(clients)[0];
  const s = io.sockets.sockets.get(socketId);
  s.disconnect();
};

const socketConnect = (io, socket, jobs) => {
  const { mode } = socket.handshake.query;
  switch (mode) {
    case modes.INIT:
      initiator(socket, jobs);
      break;
    case modes.EXEC:
      executor(io, socket, jobs);
      break;
    case modes.VIEW:
      viewer(socket);
      break;
    default:
      socket.send(evt.ERR, "Invalid Mode!");
      socket.disconnect();
      break;
  }
};

const socketAuth = (socket, next) => {
  const { token } = socket.handshake.auth;
  // next(new Error("Bad Token"));
  next();
};

const applySockets = (server, jobs, options) => {
  const io = new Skio(server);
  io.on("connection", (socket) => socketConnect(io, socket, jobs));
  io.of("/").adapter.on("leave-room", (room, id) => socketDrop(io, room, id));
  return io;
};

export default applySockets;
