import {
  controlsInit,
  downloadTable,
  newSandboxDiv,
  renderTable,
  table2col
} from "./chunk-SA7APTJR.js";
import "./chunk-HJ6L54YS.js";
import "./chunk-LSEFWW72.js";
import "./chunk-SKREEF3H.js";
import {
  Menu
} from "./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 {
  copyMerge,
  getCompInit
} 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 {
  roundValueAuto
} from "./chunk-TLT4YIG3.js";
import "./chunk-KYBIQBXE.js";
import {
  select_default
} from "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// plots/geneORA.js
var tip = new Menu();
var geneORA = class _geneORA {
  static type = "geneORA";
  constructor() {
    this.type = _geneORA.type;
  }
  async init(opts) {
    if (!this.opts.holder || !this.opts.header) {
      const sandBox = newSandboxDiv(select_default(this.opts.holder.node().parentNode));
      this.opts.header = sandBox.header;
      this.opts.holder = sandBox.body;
    }
    const controlsDiv = this.opts.holder.append("div").style("display", "inline-block");
    const mainDiv = this.opts.holder.append("div").style("display", "inline-block").style("margin-left", "50px");
    const holder = mainDiv.append("div").style("display", "inline-block");
    const detailsDiv = mainDiv.append("div").style("display", "inline-block").style("vertical-align", "top").style("margin-top", "50px");
    const tableDiv = this.opts.holder.append("div").style("margin-left", "50px");
    this.dom = {
      holder,
      header: this.opts.header,
      controlsDiv,
      detailsDiv,
      tableDiv
    };
  }
  async setControls() {
    this.dom.controlsDiv.selectAll("*").remove();
    const inputs = [
      {
        label: "P-value Filter Cutoff (Linear Scale)",
        type: "number",
        chartType: "geneORA",
        settingsKey: "pvalue",
        title: "P-value significance",
        min: 0,
        max: 1
      },
      {
        label: "P-value Filter Type",
        type: "radio",
        chartType: "geneORA",
        settingsKey: "adjusted_original_pvalue",
        title: "Toggle between original and adjusted pvalues for volcano plot",
        options: [
          { label: "Adjusted", value: "adjusted" },
          { label: "Original", value: "original" }
        ]
      },
      {
        label: "Gene Set Size Filter Cutoff",
        type: "number",
        chartType: "geneORA",
        settingsKey: "gene_set_size_cutoff",
        title: "Gene set size cutoff. Helps in filtering out large gene sets",
        min: 0,
        max: 2e4
      },
      {
        label: "Filter Non-coding Genes",
        type: "checkbox",
        chartType: "geneORA",
        settingsKey: "filter_non_coding_genes",
        title: "Filter non-coding genes",
        boxLabel: ""
      }
    ];
    const geneSet = {
      label: "Gene Set Group",
      type: "dropdown",
      chartType: "geneORA",
      settingsKey: "pathway",
      title: "Display table showing original and adjusted pvalues corresponding to each significant pathway",
      boxLabel: ""
    };
    geneSet.options = this.app.opts.genome.termdbs.msigdb.analysisGenesetGroups;
    if (!this.settings.pathway) {
      this.settings.pathway = "-";
    }
    inputs.push(geneSet);
    this.components = {
      controls: await controlsInit({
        app: this.app,
        id: this.id,
        holder: this.dom.controlsDiv,
        inputs
      })
    };
    this.components.controls.on("downloadClick.geneORA", () => {
      downloadTable(this.gene_ora_table_rows, this.gene_ora_table_cols);
    });
  }
  getState(appState) {
    const config = appState.plots.find((p) => p.id === this.id);
    if (!config) throw `No plot with id='${this.id}' found`;
    return {
      config
    };
  }
  async main() {
    this.config = JSON.parse(JSON.stringify(this.state.config));
    this.settings = this.config.settings.geneORA;
    await this.setControls();
    this.dom.header.html(
      this.config.geneORAparams.sample_genes.split(",").length + ' genes <span style="font-size:.8em;opacity:.7">GENE SET OVERREPRESENTATION ANALYSIS</span>'
    );
    render_geneORA(this);
  }
};
async function render_geneORA(self) {
  if (self.settings.pathway != "-") {
    self.dom.detailsDiv.selectAll("*").remove();
    self.dom.tableDiv.selectAll("*").remove();
    self.config.geneORAparams.geneSetGroup = self.settings.pathway;
    self.config.geneORAparams.filter_non_coding_genes = self.settings.filter_non_coding_genes;
    const wait = self.dom.detailsDiv.append("div").text("Loading...");
    let output;
    try {
      output = await rungeneORA(self.config.geneORAparams);
      wait.remove();
      if (output.error) {
        throw output.error;
      }
    } catch (e) {
      alert("Error: " + e);
      return;
    }
    const table_stats = table2col({ holder: self.dom.detailsDiv });
    const [t1, t2] = table_stats.addRow();
    t2.style("text-align", "center").style("font-size", "0.8em").style("opacity", "0.8").text("COUNT");
    const addStats = [
      //{
      //	label: 'Sample genes',
      //	values: self.config.geneORAparams.sample_genes.split(',').length
      //},
      {
        label: "Gene sets analyzed",
        values: output.num_pathways
      }
    ];
    if (self.config.geneORAparams.background_genes) {
      addStats.push({
        label: "Background genes",
        values: self.config.geneORAparams.background_genes.split(",").length
      });
    }
    for (const dataRow of addStats) {
      const [td1, td2] = table_stats.addRow();
      td1.text(dataRow.label);
      td2.style("text-align", "end").text(dataRow.values);
    }
    self.gene_ora_table_cols = [
      { label: "Gene set group" },
      { label: "Original p-value (linear scale)" },
      { label: "Adjusted p-value (linear scale)" },
      { label: "Gene set size" },
      { label: "Gene set hits" }
    ];
    self.gene_ora_table_rows = [];
    for (const pathway of output.pathways) {
      if (self.settings.adjusted_original_pvalue == "adjusted" && self.settings.pvalue >= pathway.p_value_adjusted && self.settings.gene_set_size_cutoff > pathway.gene_set_size) {
        self.gene_ora_table_rows.push([
          { value: pathway.pathway_name },
          { value: roundValueAuto(pathway.p_value_original) },
          { value: roundValueAuto(pathway.p_value_adjusted) },
          { value: pathway.gene_set_size },
          { value: pathway.gene_set_hits }
        ]);
      } else if (self.settings.adjusted_original_pvalue == "original" && self.settings.pvalue >= pathway.p_value_original && self.settings.gene_set_size_cutoff > pathway.gene_set_size) {
        self.gene_ora_table_rows.push([
          { value: pathway.pathway_name },
          { value: roundValueAuto(pathway.p_value_original) },
          { value: roundValueAuto(pathway.p_value_adjusted) },
          { value: pathway.gene_set_size },
          { value: pathway.gene_set_hits }
        ]);
      }
    }
    const d_ora = self.dom.tableDiv.append("div");
    renderTable({
      columns: self.gene_ora_table_cols,
      rows: self.gene_ora_table_rows,
      div: d_ora,
      showLines: true,
      maxHeight: "30vh",
      resize: true
    });
  }
}
async function getPlotConfig(opts, app) {
  try {
    const config = {
      //idea for fixing nav button
      //samplelst: { groups: app.opts.state.groups}
      settings: {
        geneORA: {
          pvalue: 0.05,
          adjusted_original_pvalue: "adjusted",
          pathway: void 0,
          gene_set_size_cutoff: 2e3,
          filter_non_coding_genes: true
        },
        controls: { isOpen: true }
      }
    };
    return copyMerge(config, opts);
  } catch (e) {
    throw `${e} [geneORA getPlotConfig()]`;
  }
}
var geneORAInit = getCompInit(geneORA);
var componentInit = geneORAInit;
function makeChartBtnMenu(holder, chartsInstance) {
  chartsInstance.prepPlot({
    config: {
      chartType: "geneORA"
    }
  });
}
async function rungeneORA(body) {
  return await dofetch3("genesetOverrepresentation", { body });
}
export {
  componentInit,
  geneORAInit,
  getPlotConfig,
  makeChartBtnMenu
};
//# sourceMappingURL=geneORA-S3KQMBYL.js.map
