import {
  GeneSetEditUIwithTabs,
  fillTermWrapper
} 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 {
  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 "./chunk-TLT4YIG3.js";
import "./chunk-KYBIQBXE.js";
import "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// plots/geneset.js
var GenesetComp = class _GenesetComp {
  static type = "geneset";
  // type: 'geneset'
  // dom: {
  // 	[domKey: string]: any // usually a d3-selection
  // }
  // opts: {
  // 	holder: any
  // 	genes: string[]
  // 	mode: 'geneVariant' | 'geneExpression'
  // 	callback: CallbackArg
  // 	reactsTo?: (action: any) => boolean
  // 	showWaitMessage?: (waitDiv: any) => void
  // }
  constructor(opts) {
    this.type = _GenesetComp.type;
    this.dom = {
      holder: opts.holder.style("position", "relative").style("min-height", "300px").style("margin", "0px 20px").style("max-width", "1000px"),
      body: opts.holder.append("div"),
      loadingOverlay: opts.holder.append("div").attr("class", "sjpp-spinner").style("display", "none").style("position", "absolute").style("background-color", "#fff").style("z-index", 10).style("opacity", "0.5")
      //.style('width', '100%')
      //.style('height', '100%')
    };
  }
  init() {
    if (this.opts.reactsTo) this.reactsTo = this.opts.reactsTo;
  }
  getState(appState) {
    const config = appState.plots.find((p) => p.id === this.id);
    return {
      vocab: appState.vocab,
      filter0: appState.termfilter.filter0,
      config
    };
  }
  async main() {
    this.dom.body.selectAll("*").remove();
    this.dom.loadingOverlay.style("display", "");
    this.noWait().catch(console.warn);
  }
  async noWait() {
    const abortCtrl = new AbortController();
    try {
      const [genes, stale] = await this.api.detectStale(() => this.getGenes({ signal: abortCtrl.signal }), {
        abortCtrl
      });
      if (stale) return;
      if (!genes?.length) this.render();
      else this.opts.callback(this.api, genes);
    } catch (e) {
      if (e == "stale sequenceId" || e.name == "AbortError") return;
      if (e?.code === "CACHE_BUSY" && this.opts.showWaitMessage) {
        if (window.confirm(e.message || String(e))) this.main();
        return;
      }
      if (this.opts.showWaitMessage) {
        this.dom.body.style("margin", "20px").html(e);
      }
      throw e;
    }
  }
  async getGenes({ signal }) {
    const genes = this.opts.genes;
    const settings = this.state.config.settings;
    if (this.opts.genes) {
      if (!Array.isArray(this.opts.genes) || this.opts.genes.length == 0) throw ".genes[] is not non-empty array";
      return await this.getTwLst(this.opts.genes);
    }
    if (this.opts.showEditUI) {
      return [];
    }
    let waitDiv;
    if (this.opts.showWaitMessage) {
      waitDiv = this.dom.body.append("div").style("margin", "20px");
      this.opts.showWaitMessage(waitDiv);
    }
    let data;
    if (this.opts.mode == "geneVariant") {
      const body = {
        genome: this.state.vocab.genome,
        dslabel: this.state.vocab.dslabel
      };
      if (settings.maxGenes) body.maxGenes = settings.maxGenes;
      if (settings.geneFilter) body.geneFilter = settings.geneFilter;
      if (this.state.filter0) body.filter0 = this.state.filter0;
      data = await dofetch3("termdb/topMutatedGenes", { body, signal });
    } else if (this.opts.mode == "geneExpression") {
      const body = {
        genome: this.state.vocab.genome,
        dslabel: this.state.vocab.dslabel,
        maxGenes: settings.maxGenes
      };
      if (this.state.filter0) body.filter0 = this.state.filter0;
      data = await dofetch3("termdb/topVariablyExpressedGenes", { body, signal });
    } else {
      throw "unknown opts.mode [geneset.js]";
    }
    if (!data) throw "invalid server response";
    if (data.error) {
      if (data.status === 429) throw Object.assign(new Error(data.error), { code: "CACHE_BUSY" });
      throw data.error;
    }
    if (!data.genes) return [];
    waitDiv.remove();
    this.dom.loadingOverlay?.style("display", "none");
    return await this.getTwLst(data.genes);
  }
  async getTwLst(genes) {
    return await Promise.all(
      // do tempfix of "data.genes.slice(0,3).map" for faster testing
      genes.map(
        async (i) => typeof i == "string" ? await fillTermWrapper({ term: { gene: i, type: this.opts.mode } }, this.app.vocabApi) : await fillTermWrapper({ term: { gene: i.gene || i.name, type: this.opts.mode } }, this.app.vocabApi)
      )
    );
  }
  async render() {
    if (!this.dom?.holder) return;
    const settings = this.state.config.settings;
    this.dom.body.append("p").html(
      `Define a gene set to launch <span style='text-transform: capitalize'>${this.state.config.toolName.toLowerCase()}</span>.`
    );
    new GeneSetEditUIwithTabs(
      {
        holder: this.dom.body.append("div"),
        genome: this.opts.genome,
        mode: this.opts.mode,
        vocabApi: this.app.vocabApi,
        //  await vocabInit({ state: { genome: gdcGenome, dslabel: gdcDslabel } }),
        maxNumGenes: settings.maxGenes,
        callback: async (result) => {
          const twlst = await Promise.all(
            result.geneList.map(async (i) => {
              return fillTermWrapper({ term: { gene: i.gene || i.name || i, type: this.opts.mode } }, this.app.vocabApi);
            })
          );
          this.opts.callback(this.api, twlst);
        }
      }
      /*as GeneSetEditArg*/
    );
    this.dom.loadingOverlay?.style("display", "none");
  }
  destroy() {
    this.dom.holder.selectAll("*").remove();
    this.dom.holder.remove();
    for (const key in this.dom) {
      delete this.dom[key];
    }
  }
};
var genesetInit = getCompInit(GenesetComp);
var componentInit = genesetInit;
async function getPlotConfig(opts = {}, app) {
  const config = copyMerge(
    {
      chartType: "geneset"
    },
    opts
  );
  return config;
}
export {
  componentInit,
  genesetInit,
  getPlotConfig
};
//# sourceMappingURL=geneset-SNM4M6UM.js.map
