const baseCommand = "node";
const suiteEntry = "tests/assets/suite/runner.js";
const pipelineMapping = [
  {
    id: 0,
    pipeline: [{ name: "primary" }, { name: "secondary", delay: 5000 }],
  },
];

const buildCommon = (jobRequest) => {
  const { isTriage, ignore, region, testNames } = jobRequest;
  const command = [baseCommand, suiteEntry];
  // Apply Common Flags
  if (isTriage) command.push(`isTriage=${isTriage}`);
  if (ignore && ignore.length > 0) console.log("Would ignore", ignore);
  if (region) command.push(`region=${region}`);

  // Return new request
  return { ...jobRequest, command };
};

const buildManual = (jobReq) => {
  const { command, testNames } = jobReq;
  if (testNames.length > 1)
    throw Error("Currently only 1 test can be selected!");

  command.push(`test=${testNames[0]}`);

  return { ...jobReq, command };
};

const buildTags = (jobReq) => {
  const { command, tags, testNames } = jobReq;
  if (testNames && testNames.length > 0) {
    return console.log("Would run tags as manual");
  }
  const arg = Buffer.from(JSON.stringify(tags), "utf8").toString("base64");
  command.push(`tags=${arg}`);
  return { ...jobReq, command };
};

const buildPipeline = (jobReq, socketId) => {
  const { command, pipeline } = jobReq;
  const { __test: test } = pipeline;
  if (!test) throw Error("__test is required for pipeline jobs!");
  pipeline.dashboardSocketId = socketId;
  const arg = Buffer.from(JSON.stringify(pipeline), "utf8").toString("base64");
  command.push(`pipeline=${arg}`);
  command.push(`test=${test}`);
  return { ...jobReq, command };
};

export default function jobBuilder(jobRequest, id) {
  console.log(jobRequest);
  const jobReq = buildCommon(jobRequest, id);
  const { pipeline, testNames, tags } = jobReq;
  if (pipeline) return buildPipeline(jobReq, id);
  else if (tags) return buildTags(jobReq);
  else if (testNames) return buildManual(jobReq); //TODO currently does nothing
  else throw Error("At least 1 'pipeline or tags or testNames' is required! ");
}
