const allowedCriterion = [
  "TelescopeRangeCriterion",
  "RangeCriterion",
  "TelescopeThresholdCriterion",
  "ThresholdCriterion",
];

export function plotCriteria(svg, width, height, y, metadata, id) {
  const yScaleType = metadata.plotConfiguration.y.scale || "linear";
  for (const criterion of allowedCriterion) {
    if (metadata.criteriaReport.hasOwnProperty(criterion)) {
      const config = metadata.criteriaReport[criterion].config;
      switch (criterion) {
        case "TelescopeRangeCriterion":
          plotRange(
            config.min_value[0][2],
            config.max_value[0][2],
            svg,
            width,
            y,
            id,
            yScaleType
          );
          break;
        case "RangeCriterion":
          plotRange(
            config.min_value,
            config.max_value,
            svg,
            width,
            y,
            id,
            yScaleType
          );
          break;
        case "TelescopeThresholdCriterion":
          plotThreshold(
            config.above,
            config.threshold[0][2],
            svg,
            width,
            height,
            y,
            id
          );
          break;
        case "ThresholdCriterion":
          plotThreshold(
            config.above,
            config.threshold,
            svg,
            width,
            height,
            y,
            id
          );
          break;
      }
      updateBadgeCriteria(id, metadata, criterion);
      // Only one criterion should be present, so break after handling
      break;
    }
  }
}

function plotRange(minVal, maxVal, svg, width, y, id, yScaleType) {
  const yMin = y.domain()[0];
  if (yScaleType === "log" && minVal <= 0) {
    minVal = yMin;
    console.warn(
      `Minimum value for log scale adjusted to ${yMin} to avoid negative or zero values.`
    );
  }

  // Color region between two lines
  svg
    .append("rect")
    .attr("x", 0)
    .attr("y", y(maxVal))
    .attr("width", width)
    .attr("height", y(minVal) - y(maxVal))
    .attr("fill", "#28a745")
    .attr("opacity", 0.15)
    .attr("clip-path", `url(#clip-${id})`);

  // Min horizontal line
  svg
    .append("line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", y(minVal))
    .attr("y2", y(minVal))
    .attr("stroke", "#28a745")
    .attr("stroke-width", 2)
    .attr("stroke-dasharray", "4,2")
    .attr("clip-path", `url(#clip-${id})`);

  // Max horizontal line
  svg
    .append("line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", y(maxVal))
    .attr("y2", y(maxVal))
    .attr("stroke", "#28a745")
    .attr("stroke-width", 2)
    .attr("stroke-dasharray", "4,2")
    .attr("clip-path", `url(#clip-${id})`);
}

function plotThreshold(above, threshold, svg, width, height, y, id) {
  if (above) {
    // Color above threshold
    svg
      .append("rect")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", width)
      .attr("height", y(threshold))
      .attr("fill", "#28a745")
      .attr("opacity", 0.15)
      .attr("clip-path", `url(#clip-${id})`);
  } else {
    // Color below threshold
    svg
      .append("rect")
      .attr("x", 0)
      .attr("y", y(threshold))
      .attr("width", width)
      .attr("height", height - y(threshold))
      .attr("fill", "#28a745")
      .attr("opacity", 0.15)
      .attr("clip-path", `url(#clip-${id})`);
  }
  // Horizontal threshold line
  svg
    .append("line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", y(threshold))
    .attr("y2", y(threshold))
    .attr("stroke", "#28a745")
    .attr("stroke-width", 2)
    .attr("stroke-dasharray", "4,2")
    .attr("clip-path", `url(#clip-${id})`);
}

// --> TBD add call to function inside to update also color of table in the summary page
function updateBadgeCriteria(id, metadata, criterion) {
  // Update criteria badge color upon criteria result
  const badgerElem = document.getElementById(id).parentElement;
  if (metadata.criteriaReport[criterion].result) {
    updateBadgeClass(badgerElem, "badger-success");
  } else {
    updateBadgeClass(badgerElem, "badger-danger");
  }
}

export function badgeCriteriaNone(id) {
  const badgerElem = document.getElementById(id).parentElement;
  console.debug("Badge set to NONE for plot: " + id + ".");
  updateBadgeClass(badgerElem, "badger-null");
}

function updateBadgeClass(elem, newClass) {
  const validClasses = ["badger-success", "badger-danger", "badger-null"];
  if (!elem || !validClasses.includes(newClass)) return;

  validClasses.forEach((cls) => elem.classList.remove(cls));
  elem.classList.add(newClass);

  const badgeText = {
    "badger-success": "CRITERIA: OK",
    "badger-danger": "CRITERIA: FAIL",
    "badger-null": "CRITERIA: NONE",
  };
  elem.setAttribute("data-badger-right", badgeText[newClass]);
}
