import { v4 } from "uuid";
import applyJob from "./kubernetes.js";

export default class JobManager {
  constructor(clientMaxJobs) {
    this.clientMaxJobs = clientMaxJobs;
    this.clients = {};
  }

  getJob(clientId, jobId) {
    return this.clients[clientId].jobs.find((j) => j.id === jobId);
  }

  getJobById(jobId) {
    for (var client of Object.values(this.clients)) {
      const job = client.jobs.find((j) => j.id === jobId);
      if (!job) continue;
      return job;
    }
  }

  pushLog(jobId, log) {
    const job = this.getJobById(jobId);
    if (log instanceof Array) job.log.push(...log);
    else job.log.push(log);
  }

  closeJob(jobId, exitcode) {
    const job = this.getJobById(jobId);
    job.exitcode = exitcode;
  }

  newJob(jobRequest, id) {
    if (!jobRequest) throw Error("Request Must Be Object!");
    if (!this.clients[id]) this.clients[id] = { jobs: [] };
    const client = this.clients[id];
    if (
      client.jobs.filter((j) => j.exitcode === undefined).length >=
      this.clientMaxJobs
    )
      throw Error("Client's Active Jobs Exceeded!");
    const job = { ...jobRequest };
    job.id = v4();
    job.log = [];
    this.clients[id].jobs.push(job);
    applyJob(job);
    return { ...job };
  }

  removeJob(clientId, id) {
    this.clients[clientId].jobs = this.clients[clientId].jobs.filter(
      (j) => j.id !== id
    );
  }
}
