import {
  getPillNameDefault,
  make_radios,
  sayerror,
  set_hiddenvalues,
  throwMsgWithFilePathAndFnName
} from "./chunk-SA7APTJR.js";
import "./chunk-HJ6L54YS.js";
import "./chunk-LSEFWW72.js";
import "./chunk-SKREEF3H.js";
import "./chunk-HYOEWQ5P.js";
import "./chunk-HBW42TDT.js";
import "./chunk-G6O3URDN.js";
import "./chunk-FN5XPUPH.js";
import "./chunk-IIT367QZ.js";
import "./chunk-RZGEKL77.js";
import "./chunk-UI7OCM2A.js";
import "./chunk-YZK37YCC.js";
import "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import {
  copyMerge
} from "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import "./chunk-NOEAT6CX.js";
import "./chunk-4UWS5Y3N.js";
import "./chunk-DD4R5P6W.js";
import "./chunk-JNITUVXP.js";
import "./chunk-KSGA62R2.js";
import "./chunk-LOZEKOES.js";
import "./chunk-TOU7EVFQ.js";
import "./chunk-OAWQ6LOO.js";
import "./chunk-TLT4YIG3.js";
import "./chunk-KYBIQBXE.js";
import "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// termsetting/handlers/condition.ts
var cutoffGrades = [1, 2, 3, 4, 5];
function getHandler(self) {
  return {
    getPillName(d) {
      return getPillNameDefault(self, d);
    },
    getPillStatus() {
      return getPillStatus(self);
    },
    showEditMenu(div) {
      if (self.q.mode == "discrete") {
        return showMenu_discrete(self, div);
      }
      if (self.q.mode == "binary" || self.q.mode == "cuminc" || self.q.mode == "cox") {
        return showMenu_cutoff(self, div);
      }
      console.error("invalid q.mode:", self.q.mode);
      throw "invalid q.mode";
    }
    // async postMain() {
    // 	const body = self.opts.getBodyParams?.() || {} //make sure term1_q is added
    // 	const data = await self.vocabApi.getCategories(self.term, self.filter!, body)
    // 	//not really sure this is necessary but it's consistent across other handlers
    // 	self.category2samplecount = []
    // 	for (const d of data.lst) {
    // 		self.category2samplecount.push({
    // 			key: d.key,
    // 			label: d.label,
    // 			count: d.samplecount
    // 		})
    // 		// }
    // 	}
    // }
  };
}
function getPillStatus(self) {
  const text = self.q?.name || self.q?.reuseId;
  if (text) return { text };
  if (self.q.mode == "discrete") {
    if (self.q.breaks?.length) {
      return { text: self.q.breaks.length + 1 + " groups" };
    } else {
      if (self.q.bar_by_grade) {
        if (self.q.value_by_max_grade) return { text: "Max. Grade" };
        if (self.q.value_by_most_recent) return { text: "Most Recent Grade" };
        if (self.q.value_by_computable_grade) return { text: "Any Grade" };
        return { text: "Error: unknown grade setting", bgcolor: "red" };
      }
      if (self.q.bar_by_children) return { text: "Sub-condition" };
    }
  }
  if (self.q.mode == "binary") {
    return {
      text: self.usecase?.target == "regression" ? self.data.q.groups.find((x) => x.name != self.data.refGrp).name : "binary"
    };
  }
  if (self.q.mode == "cuminc" || self.q.mode == "cox") {
    if (!self.q.breaks || self.q.breaks.length == 0) throwMsgWithFilePathAndFnName("Missing q.breaks");
    return { text: `Grades ${self.q.breaks[0]}-5` };
  }
  return {};
}
async function showMenu_discrete(self, div) {
  const value_type_div = div.append("div").style("margin", "10px 0px 10px 5px").style("border-left", "solid 1px #ededed");
  value_type_div.append("div").style("display", "inline-block").style("margin", "0px 0px 5px 5px").style("color", "rgb(136, 136, 136)").text("Grade type:");
  const value_type_select = value_type_div.append("select").style("display", "inline").style("margin", "0px 10px").on("change", () => {
    const i = value_type_select.property("selectedIndex");
    self.q.bar_by_grade = i != 3;
    self.q.bar_by_children = i == 3;
    self.q.value_by_max_grade = i == 0;
    self.q.value_by_most_recent = i == 1;
    self.q.value_by_computable_grade = i == 2 || i == 3;
    self.dom.tip.hide();
    self.api.runCallback();
  });
  value_type_select.append("option").text("Max grade per patient");
  value_type_select.append("option").text("Most recent grade per patient");
  value_type_select.append("option").text("Any grade per patient");
  if (self.term.subconditions) {
    value_type_select.append("option").text("Sub-conditions");
  }
  value_type_select.property(
    "selectedIndex",
    self.q.bar_by_children ? 3 : self.q.value_by_computable_grade ? 2 : self.q.value_by_most_recent ? 1 : 0
  );
  if (self.q.bar_by_children) {
    return;
  }
  const breaksSelectorDiv = div.append("div").style("margin", "20px 0px 10px 5px").style("border-left", "solid 1px #ededed");
  breaksSelectorDiv.append("div").text("Divide grades into groups (optional):").style("margin", "0px 0px 10px 5px").style("color", "rgb(136, 136, 136)");
  const holder = breaksSelectorDiv.append("div").style("display", "flex").style("align-items", "start").style("margin-left", "10px").style("width", "100%");
  const gradeValuesDiv = holder.append("div").style("margin-right", "20px");
  const rangeNameDiv = holder.append("div").style("display", "grid").style("grid-template-columns", "auto auto").style("column-gap", "20px").style("align-items", "center").style("margin-right", "5px");
  gradeValuesDiv.append("div").style("margin-bottom", "5px").style("color", "rgb(136, 136, 136)").text("Cutoff grades");
  const textarea = gradeValuesDiv.append("textarea").style("width", "100px").style("height", "70px").on("keyup", textarea2gradeUI);
  gradeValuesDiv.append("div").style("font-size", ".6em").style("margin-left", "1px").style("color", "#858585").html("Enter numeric values </br>seperated by ENTER");
  if (self.q.breaks?.length) {
    textarea.property("value", self.q.breaks.join("\n"));
  }
  textarea2gradeUI();
  function textarea2gradeUI() {
    rangeNameDiv.selectAll("*").remove();
    const breaks = textarea2breaks();
    if (!breaks.length) {
      delete self.q.breaks;
      delete self.q.groups;
      return;
    }
    if (!self.term.values) throwMsgWithFilePathAndFnName(`Missing term values`);
    const grades = Object.keys(self.term.values).filter((g) => !self.term.values?.[g].uncomputable).map(Number).sort((a, b) => a - b);
    const groups = getGroups(grades, breaks);
    rangeNameDiv.append("div").style("margin-bottom", "3px").style("color", "rgb(136, 136, 136)").text("Range");
    rangeNameDiv.append("div").style("margin-bottom", "3px").style("color", "rgb(136, 136, 136)").text("Label");
    for (const [i, g] of groups.entries()) {
      rangeNameDiv.append("div").text(g.name.replace(/Grades* /, ""));
      rangeNameDiv.append("div").append("input").attr("type", "text").property("value", g.name).style("margin", "2px 0px").on("change", function() {
        groups[i].name = this.value;
      });
    }
    self.q.breaks = breaks;
    self.q.groups = groups;
  }
  function textarea2breaks() {
    const str = textarea.property("value").trim();
    if (!str) return [];
    const lst = [...new Set(str.split("\n"))];
    const breaks = [];
    for (const x of lst) {
      const b = Number(x);
      if (!Number.isInteger(b)) {
        sayerror(div, "cutoff grade must be an integer value");
        return [];
      }
      if (b < 1 || b > 5) {
        sayerror(div, `cutoff grade must be within grades 1-5`);
        return [];
      }
      breaks.push(b);
    }
    if (!breaks.length) return [];
    return breaks.sort((i, j) => i - j);
  }
  div.append("button").text("Apply").style("margin", "10px").on("click", (event) => {
    event.target.disabled = true;
    event.target.innerHTML = "Loading...";
    self.api.runCallback();
  });
}
function showMenu_cutoff(self, div) {
  const holder = div.append("div").style("margin", "10px").style("display", "grid").style("grid-template-columns", "auto auto").style("gap", "20px");
  holder.append("div").text("Grade cutoff").style("opacity", 0.4);
  const sd = holder.append("div");
  const gradeSelect = sd.append("select").on("change", changeGradeSelect);
  for (const i of cutoffGrades) {
    gradeSelect.append("option").text(self.term.values?.[i].label);
  }
  gradeSelect.property("selectedIndex", self.q.breaks[0] - 1);
  holder.append("div").text(self.q.mode == "binary" ? "Group 1" : "Censored").style("opacity", 0.4);
  const g1n = holder.append("div").style("opacity", 0.4);
  holder.append("div").text(self.q.mode == "binary" ? "Group 2" : "Event").style("opacity", 0.4);
  const g2n = holder.append("div").style("opacity", 0.4);
  changeGradeSelect();
  function changeGradeSelect() {
    const grade = gradeSelect.property("selectedIndex") + 1;
    g1n.selectAll("*").remove();
    g2n.selectAll("*").remove();
    const grades = Object.keys(self.term.values).map(Number).sort((a, b) => a - b);
    for (const i of grades) {
      if (i < grade) {
        g1n.append("div").text(self.term.values?.[i].label);
      } else {
        g2n.append("div").text(self.term.values?.[i].label);
      }
    }
  }
  const timeUnit = self.vocabApi.termdbConfig.timeUnit;
  let timeScaleChoice;
  if (self.q.mode == "cox") {
    timeScaleChoice = self.q.timeScale;
    holder.append("div").text("Time axis").style("opacity", 0.4);
    const options = [
      {
        label: timeUnit.charAt(0).toUpperCase() + timeUnit.slice(1),
        value: "time"
      },
      { label: "Age", value: "age" }
    ];
    if (self.q.timeScale == "age") {
      options[1].checked = true;
    } else {
      options[0].checked = true;
    }
    make_radios({
      holder: holder.append("div"),
      options,
      styles: { padding: "" },
      callback: (v) => timeScaleChoice = v
    });
  }
  div.append("button").text("Apply").style("margin", "10px").on("click", (event) => {
    if (!self.q.breaks || self.q.breaks.length == 0) throwMsgWithFilePathAndFnName("Missing q.breaks");
    const grade = gradeSelect.property("selectedIndex") + 1;
    self.q.breaks[0] = grade;
    if (self.q.mode == "binary") {
      const grades = Object.keys(self.term.values).map(Number).sort((a, b) => a - b);
      self.q.groups = getGroups(grades, self.q.breaks);
      self.refGrp = self.q.groups[0].name;
    }
    if (self.q.mode == "cox") self.q.timeScale = timeScaleChoice;
    event.target.disabled = true;
    event.target.innerHTML = "Loading...";
    self.api.runCallback();
  });
}
function getGroups(grades, breaks) {
  grades.sort((a, b2) => a - b2);
  const groups = [];
  let group = { values: [] };
  let b;
  for (const g of grades) {
    if (breaks.includes(g)) {
      b = g;
      const max = Math.max(...group.values);
      if (!groups.length) {
        if (group.values.length == 1) {
          if (group.values[0] !== 0) throw "unexpected group value";
          group.name = "Grade 0";
        } else {
          if (group.values.length == 2 && group.values.includes(-1) && group.values.includes(0)) {
            group.name = "Not tested/Grade 0";
          } else {
            group.name = group.values.includes(-1) ? `Not tested/Grade 0 - Grade ${max}` : `Grades 0-${max}`;
          }
        }
      } else {
        group.name = group.values.length == 1 ? `Grade ${group.values[0]}` : `${group.name}-${max}`;
      }
      groups.push(group);
      group = {
        name: `Grade ${b}`,
        values: [g]
      };
    } else {
      group.values.push(g);
    }
  }
  group.name = `Grades ${b}-5`;
  groups.push(group);
  return groups;
}
function fillTW(tw, vocabApi, defaultQ) {
  set_hiddenvalues(tw.q, tw.term);
  if (defaultQ) {
    copyMerge(tw.q, defaultQ);
  }
  if (!Object.keys(tw.q).includes("mode")) tw.q.mode = "discrete";
  if (!tw.q.valueFor) {
    const q = tw.q;
    if (!q.bar_by_grade && !q.bar_by_children) q.bar_by_grade = true;
    tw.q.valueFor = tw.q.bar_by_children ? "children" : "grade";
  }
  if (tw.q.valueFor == "grade") {
    if (tw.q.value_by_max_grade || tw.q.value_by_most_recent || tw.q.value_by_computable_grade) {
    } else {
      tw.q.value_by_max_grade = true;
    }
  }
  if (tw.q.mode == "binary" || tw.q.mode == "cox" || tw.q.mode == "cuminc") {
    const defaultBreak = tw.q.mode == "binary" ? 1 : 3;
    if (!tw.q.breaks?.length) tw.q.breaks = [defaultBreak];
    if (tw.q.breaks.length != 1 || ![1, 2, 3, 4, 5].includes(tw.q.breaks[0])) throw "invalid tw.q.breaks";
  }
  if (tw.q.valueFor == "grade") {
    if (tw.q.breaks?.length) {
      if (!tw.term.values) throw "missing term.values";
      if (tw.q.mode == "discrete" || tw.q.mode == "binary") {
        const grades = Object.keys(tw.term.values).filter((g) => tw.q.mode == "discrete" ? !tw.term.values?.[g].uncomputable : g).map(Number).sort((a, b) => a - b);
        tw.q.groups = getGroups(grades, tw.q.breaks);
      }
    }
    if (tw.q.mode == "cox") {
      if (!tw.q.timeScale) tw.q.timeScale = "time";
      if (!["age", "time"].includes(tw.q.timeScale)) throw "invalid q.timeScale";
    }
  }
}
export {
  fillTW,
  getHandler
};
//# sourceMappingURL=condition-HDVYPJJD.js.map
