import evt from "./events.js";

export const initiator = (socket, jobs) => {
  const jobStr = socket.handshake.query.job;
  const jobReq = JSON.parse(jobStr);

  if (!jobReq || !(jobReq instanceof Object))
    throw Error("No 'job' was included in the handshake query");

  const job = jobs.newJob(jobReq, socket.id);
  socket.join(job.id);
  socket.emit(evt.JOB_CRT, job.id);
};

export const executor = (io, socket, jobs) => {
  const jobId = socket.handshake.query.jobId;
  if (!jobId) throw Error("No 'jobId' was included in the handshake query");

  socket.join(jobId);
  socket.on(evt.JOB_REP, function onReport(log) {
    jobs.pushLog(jobId, log);
    io.to(jobId).emit(evt.JOB_LOG, log);
  });
  socket.on(evt.JOB_CLS, function onClose(code) {
    jobs.closeJob(jobId, code);
    io.to(jobId).emit(evt.JOB_CLS, code);
  });
};

export const viewer = (socket) => {
  const jobId = socket.handshake.query.jobId;
  if (!jobId) throw Error("No 'jobId' was included in the handshake query");
  socket.join(jobId);
};
