import {
  mclasscolor2table
} from "./chunk-SA7APTJR.js";
import {
  aa2gmcoord,
  rna2gmcoord
} from "./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 {
  dofetch3
} from "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import "./chunk-NOEAT6CX.js";
import {
  dtcnv,
  dtfusionrna,
  dtsnvindel,
  mclass,
  mclasscnvgain,
  mclasscnvloss,
  mclassfusionrna
} from "./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";

// mds3/customdata.inputui.js
function customdata_inputui_default(block) {
  if (!block.usegm) {
    return;
  }
  const div = block.tip.d.append("div").style("margin", "20px");
  div.append("p").text(`Add mutation and/or fusion to show over ${block.usegm.name} ${block.usegm.isoform}`);
  const textarea2 = div.append("textarea").attr("cols", "50").attr("rows", "5").property("placeholder", "Enter data");
  textarea2.node().focus();
  const nameinput = div.append("div").append("input").attr("type", "text").style("width", "130px").property("placeholder", "Dataset name");
  const row = div.append("div").style("margin-top", "5px");
  const select = row.append("select");
  select.append("option").text("Codon position");
  select.append("option").text("RNA position");
  select.append("option").text("Genomic position");
  row.append("button").style("margin-left", "5px").text("Submit").on("click", async () => {
    const v = textarea2.property("value");
    if (v == "") return;
    says.style("display", "none");
    const selecti = select.node().selectedIndex, mlst = [], bad = [];
    for (const line0 of v.trim().split("\n")) {
      const line = line0.trim();
      if (!line) continue;
      const l = line.split(line.includes("	") ? "	" : line.includes(",") ? "," : " ");
      try {
        if (l.length == 3 || l.length == 4) {
          if (Number.isFinite(Number(l[2]))) {
            parseCnv(l, mlst, selecti, block);
          } else {
            parseMutation(l, mlst, selecti, block);
          }
          continue;
        }
        if (l.length == 6 || l.length == 7) {
          await parseFusion(l, mlst, selecti, block);
          continue;
        }
        throw `Line="${l}" does not match the mutation, fusion, or cnv format. Please review.`;
      } catch (e) {
        bad.push(line + ": " + (e.message || e));
      }
    }
    if (mlst.find((m) => m.sample) && mlst.find((m) => !m.sample)) {
      bad.push("sample name is provided for some but not all variants");
    }
    if (bad.length) {
      says.style("display", "block").text("Rejected: " + bad.join("\n"));
    }
    if (mlst.length == 0) return;
    const tk = block.block_addtk_template({
      type: "mds3",
      name: nameinput.property("value") || "Custom data",
      iscustom: true,
      custom_variants: mlst
    });
    block.tk_load(tk);
  });
  row.append("button").text("Clear").style("margin-left", "5px").on("click", () => {
    textarea2.property("value", "");
    nameinput.property("value", "");
  });
  const says = div.append("div").style("display", "none", "margin-top", "20px");
  printHelp(div);
}
function parseMutation(l, mlst, selecti, block) {
  const _class = l[2].trim();
  if (!mclass[_class]) throw `Invalid mutation class=${_class}`;
  const m = {
    class: _class,
    dt: dtsnvindel,
    isoform: block.usegm.isoform,
    mname: l[0].trim()
  };
  if (!m.mname) throw "missing mutation name";
  const o = parsePositionFromGm(selecti, l[1].trim(), block.usegm);
  m.chr = o[0];
  m.pos = o[1];
  if (l[3]) m.sample = l[3];
  mlst.push(m);
}
async function parseFusion(l, mlst, selecti, block) {
  const m = {
    class: mclassfusionrna,
    dt: dtfusionrna
    // compute and assign gene1/2, chr1/2, pos1/2
  };
  if (l[6]) m.sample = l[6];
  const [gene1, isoform1, pos1, gene2, isoform2, pos2] = l;
  if (!gene1) throw "gene1 is missing";
  if (!gene2) throw "gene2 is missing";
  if (!isoform1) throw "isoform1 is missing";
  if (!isoform2) throw "isoform2 is missing";
  if (!pos1) throw "pos1 is missing";
  if (!pos2) throw "pos2 is missing";
  {
    const d = await dofetch3("genelookup", { body: { deep: 1, genome: block.genome.name, input: gene1 } });
    if (d.error) throw "invalid gene1";
    const gm = d.gmlst.find((i) => i.isoform == isoform1);
    if (!gm) throw "invalid isoform1";
    m.gene1 = gene1;
    m.chr1 = gm.chr;
    const o = parsePositionFromGm(selecti, pos1, gm);
    m.pos1 = o[1];
    m.strand1 = gm.strand;
    m.isoform1 = isoform1;
  }
  {
    const d = await dofetch3("genelookup", { body: { deep: 1, genome: block.genome.name, input: gene2 } });
    if (d.error) throw "invalid gene2";
    const gm = d.gmlst.find((i) => i.isoform == isoform2);
    if (!gm) throw "invalid isoform2";
    m.gene2 = gene2;
    m.chr2 = gm.chr;
    const o = parsePositionFromGm(selecti, pos2, gm);
    m.pos2 = o[1];
    m.strand2 = gm.strand;
    m.isoform2 = isoform2;
  }
  mlst.push(m);
}
function parseCnv(l, mlst, selecti, block) {
  const value = Number(l[2].trim());
  if (!Number.isFinite(value)) throw "CNV value is not number";
  const m = {
    chr: block.usegm.chr,
    dt: dtcnv,
    value,
    class: value > 0 ? mclasscnvgain : mclasscnvloss
  };
  if (l[3]) m.sample = l[3];
  const a = parsePositionFromGm(selecti, l[0].trim(), block.usegm), b = parsePositionFromGm(selecti, l[1].trim(), block.usegm);
  m.start = Math.min(a[1], b[1]);
  m.stop = Math.max(a[1], b[1]);
  mlst.push(m);
}
function parsePositionFromGm(selecti, str, gm) {
  const value = parseInputPosition(str, gm.chr);
  if (!Number.isInteger(value)) throw "position is not integer";
  if (selecti == 0) {
    const p = aa2gmcoord(value, gm);
    if (p == null) throw "cannot convert codon to genomic position";
    return [gm.chr, p];
  }
  if (selecti == 1) {
    const p = rna2gmcoord(value, gm);
    if (p == null) throw "cannot convert RNA position to genomic position";
    return [gm.chr, p];
  }
  if (selecti == 2) {
    return [gm.chr, value - 1];
  }
  throw "unknown selection";
}
function parseInputPosition(str, chr) {
  let value;
  if (str.includes(":")) {
    const tmp = str.split(":");
    if (tmp[0] != chr) throw `Included chromosome=${tmp[0]} does not match current chromosome position=${chr}`;
    value = Number(tmp[1]);
  } else {
    value = Number(str);
  }
  return value;
}
function printHelp(div) {
  {
    const [label, infodiv] = makeHelpDiv(div);
    label.text("Mutation format: mutation name, position, class, sample");
    infodiv.html(
      `One mutation per line. Fields are joined by tab, comma or space. Please do not use both comma and space as separator.
		<ol>
			<li>Mutation name, can be any string</li>
			<li>Mutation position</li>
			<li>Mutation class code</li>
			<li>Optional sample name</li>
		</ol>
		Position types:
		<ul><li>Codon position: integer, 1-based (do not use for noncoding gene)</li>
		<li>RNA position: integer, 1-based, beginning from transcription start site</li>
		<li>Genomic position: integer, 1-based coordinate</li></ul>`
    );
    mclasscolor2table(infodiv.append("table").style("margin-top", "3px"), true);
  }
  {
    const [label, infodiv] = makeHelpDiv(div);
    label.text("SV/fusion format: gene1, isoform1, position1, gene2, isoform2, position2, sample");
    infodiv.html(
      `Limited to two-gene fusion products. One product per line.
			Fields are joined by tab, comma or space. Please do not use both comma and space as separator.
		<ol><li>N-term gene symbol</li>
		<li>N-term gene isoform</li>
		<li>N-term gene break-end position</li>
		<li>C-term gene symbol</li>
		<li>C-term gene isoform</li>
		<li>C-term gene break-end position</li>
		<li>Optional sample name</li>
		</ol>
		Break-end position types:
		<ul><li>Codon position: integer, 1-based</li>
		<li>RNA position: integer, 1-based, beginning from transcription start site</li>
		<li>Genomic position: 1-based coordinate</li></ul>
		Either one of the isoforms must be already displayed.`
    );
  }
  {
    const [label, infodiv] = makeHelpDiv(div);
    label.text("CNV format: segment start, segment stop, CNV value, sample");
    infodiv.html(
      `One CNV segment per line. Fields are joined by tab, comma or space. Please do not use both comma and space as separator.
		<ol>
			<li>Segment start position</li>
			<li>Segment stop position</li>
			<li>Copy number change value, positive value for gain, negative value for loss. Do not use 0</li>
			<li>Optional sample name</li>
		</ol>
		Position types:
		<ul><li>Codon position: integer, 1-based (do not use for noncoding gene)</li>
		<li>RNA position: integer, 1-based, beginning from transcription start site</li>
		<li>Genomic position: integer, 1-based coordinate</li></ul>`
    );
  }
}
function makeHelpDiv(div) {
  const p = div.append("p");
  const label = p.append("span").style("opacity", 0.6);
  p.append("span").attr("class", "sja_clbtext").style("margin-left", "10px").text("Show details").on("click", (event) => {
    const show = infodiv.style("display") == "none";
    infodiv.style("display", show ? "" : "none");
    event.target.innerHTML = show ? "Hide details" : "Show details";
  });
  const infodiv = div.append("div").style("display", "none").style("margin-left", "20px").style("padding-left", "10px").style("border-left", "solid 1px black").style("color", "#858585");
  return [label, infodiv];
}
export {
  customdata_inputui_default as default,
  parseCnv,
  parseFusion,
  parseInputPosition,
  parseMutation,
  parsePositionFromGm
};
//# sourceMappingURL=customdata.inputui-AI4ZBIEP.js.map
