import axios from "axios";
import primary from "./primary.js";
import secondary1 from "./secondary1.js";
import secondary2 from "./secondary2.js";

import tertiary1 from "./tertiary1.js";
import tertiary2 from "./tertiary2.js";
import tertiary3 from "./tertiary3.js";

import single from "./single.js";
import failing from "./failing.js";

// Constants
const liveUpdateDelay = 100;
const endLiveCount = 20;
const reportingUrl = `${process.env.QUALITEER_URL}/api/dev/rabbit/TestResults`;
// Pull args
const args = process.argv.slice(2);
const test = (args.find((v) => v.includes("test=")) ?? "").replace("test=", "");
var pipeline = (args.find((v) => v.includes("pipeline=")) ?? "").replace(
  "pipeline=",
  ""
);
if (pipeline)
  pipeline = JSON.parse(Buffer.from(pipeline, "base64").toString("utf8"));

const logNow = () => console.log(Date.now());
const liveIndicator = () => {
  for (var i = 0; i < endLiveCount; i++)
    setTimeout(logNow, i * liveUpdateDelay);
};

const runTests = () => {
  console.log(pipeline);
  switch (test) {
    case "primary":
      return primary();
    case "secondary1":
      return secondary1(pipeline.testData);
    case "secondary2":
      return secondary2(pipeline.testData);
    case "tertiary1":
      return tertiary1(pipeline.testData);
    case "tertiary2":
      return tertiary2(pipeline.testData);
    case "tertiary3":
      return tertiary3(pipeline.testData);
    case "single":
      return single();
    case "failing":
      return failing();
    default:
      return single();
  }
};

// Run
liveIndicator();
setTimeout(() => {
  const status = runTests();
  if (pipeline) pipeline.testData = status.pipelineData;
  const testResult = {
    ...status,
    name: test,
    pipeline,
  };
  axios
    .post(reportingUrl, { testResult })
    .catch((e) => {
      console.log(e.response.status);
    })
    .then(() => {
      if (status.status === 1) process.exit(1);
    });
}, endLiveCount * liveUpdateDelay);
