import {
  appInit
} from "./chunk-N2SKTCDK.js";
import "./chunk-HKSNADSX.js";
import "./chunk-SKMFMGCD.js";
import "./chunk-4KY4XKJV.js";
import {
  fillTermWrapper,
  vocabInit
} 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 {
  TermTypes
} from "./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 {
  select_default
} from "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// gdc/geneExpClustering.js
async function init(arg, holder, genomes) {
  try {
    const useGenome = arg.genome || "hg38";
    const useDslabel = arg.dslabel || "GDC";
    const genome = genomes[useGenome];
    if (!genome) throw useGenome + " missing";
    const settings = arg.settings || {};
    if (typeof settings != "object") throw "arg.settings{} not object";
    if (!settings.hierCluster) settings.hierCluster = {};
    if (typeof settings.hierCluster != "object") throw "arg.settings.hierCluster{} not object";
    if (!Number.isInteger(settings.hierCluster.maxGenes)) settings.hierCluster.maxGenes = 1e3;
    if (arg.filter0 && typeof arg.filter0 != "object") throw "arg.filter0 not object";
    const vocabApi = await vocabInit({
      state: { vocab: { genome: useGenome, dslabel: useDslabel } }
    });
    vocabApi.getTermdbConfig();
    const plotAppApi = await appInit({
      debug: arg.debug,
      holder: select_default(arg.holder).select(".sja_root_holder"),
      genome,
      state: {
        genome: useGenome,
        dslabel: useDslabel,
        termfilter: { filter0: arg.filter0 },
        plots: [
          // Initialize with a geneset component, in case the genes lst is empty.
          // This will be replaced with the actual matrix/hierCluster app once
          // a valid geneset is selected.
          {
            chartType: "geneset",
            toolName: "Gene Expression Clustering",
            settings: {
              maxGenes: settings.hierCluster.maxGenes
            }
          }
        ]
      },
      app: arg.opts?.app || {},
      hierCluster: copyMerge(
        {
          reactsTo(action) {
            if (action.type.startsWith("plot_")) return action.id === this.id;
            if (action.type.startsWith("filter")) return true;
            if (action.type == "app_refresh") return true;
          },
          callbacks: {
            "firstRender.gdcHierCluster": async (hierClusterApi2) => {
              hierClusterApi2.on("firstRender.gdcHierCluster", null);
              if (!genesetCompApi) return;
              plotAppApi.dispatch({
                type: "plot_delete",
                id: genesetCompApi.id
              });
              genesetCompApi = void 0;
            }
          }
        },
        arg.opts?.hierCluster || {}
      ),
      matrix: arg.opts?.matrix || {},
      geneset: {
        mode: "geneExpression",
        // consistent with GeneSetEdit
        genome,
        genes: arg.genes,
        showEditUI: arg.opts?.geneset?.showEditUI,
        reactsTo(action) {
          if (action.type.startsWith("plot_")) return action.id === this.id;
          if (action.type.startsWith("filter")) return true;
          if (action.type == "app_refresh") return true;
        },
        showWaitMessage(div) {
          div.style("margin", "20px");
          div.append("div").text("Loading genes that are top variably expressed in current cohort...");
          div.append("div").style("font-size", ".8em").html(`
						Only up to 1000 cases with gene expression data will be used to select genes.<br>
						Genes are selected from all protein-coding genes, may take over 1 minute.
					`);
        },
        async callback(_genesetCompApi, twlst) {
          if (!_genesetCompApi) return;
          genesetCompApi = _genesetCompApi;
          if (!hierClusterApi) {
            const plotConfig = plotAppApi.getState().plots.find((p) => p.chartType == "hierCluster");
            if (plotConfig) hierClusterApi = plotAppApi.getComponents(`plots.${plotConfig.id}`);
          }
          const termgroups = [
            {
              name: "Gene Expression",
              type: "hierCluster",
              lst: twlst
            },
            ...arg.termgroups || []
          ];
          if (hierClusterApi) {
            plotAppApi.dispatch({
              type: "plot_edit",
              id: hierClusterApi.id,
              config: { termgroups }
            });
          } else {
            plotAppApi.dispatch({
              type: "plot_create",
              config: {
                chartType: "hierCluster",
                // avoid making a dictionary request when there is no gene data;
                // if there is gene data, then the arg.termgroups can be submitted and rehydrated on app/store.init()
                termgroups,
                divideBy: arg.divideBy || void 0,
                // moved default settings to gdc.hg38.js termdb[chartType].settings
                // but can still override in the runpp() argument
                settings,
                dataType: TermTypes.GENE_EXPRESSION
              }
            });
          }
        }
      },
      recover: {
        undoHtml: "Undo",
        redoHtml: "Redo",
        resetHtml: "Restore",
        hide(state) {
          return state.plots[0]?.chartType != "hierCluster";
        },
        adjustTrackedState: (state) => {
          const s = structuredClone(state);
          delete s.termfilter.filter0;
          if (s.plots) {
            for (const plot of s.plots) {
              if (!plot.termgroups) continue;
              for (const grp of plot.termgroups) {
                if (!grp.lst) continue;
                for (const tw of grp.lst) {
                  if (!tw?.term) continue;
                  delete tw.term.category2samplecount;
                  delete tw.term.values;
                }
              }
            }
          }
          return s;
        }
      }
    });
    let hierClusterApi, genesetCompApi;
    const api = {
      type: "hierCluster",
      update: async (_arg) => {
        const plotConfig = plotAppApi.getState().plots.find((p) => p.chartType == "hierCluster");
        if (!hierClusterApi) {
          if (plotConfig) hierClusterApi = plotAppApi.getComponents(`plots.${plotConfig.id}`);
        }
        if (_arg.genes) {
          const t0 = plotConfig.termgroups.find((g) => g.type == "hierCluster");
          plotAppApi.dispatch({
            type: "plot_edit",
            id: hierClusterApi.id,
            config: {
              termgroups: [
                {
                  name: t0.name,
                  type: "hierCluster",
                  lst: await Promise.all(
                    _arg.genes.map(async (g) => {
                      return await fillTermWrapper(
                        {
                          term: { gene: g.gene, type: "geneExpression", name: g.gene }
                        },
                        vocabApi
                      );
                    })
                  )
                }
              ]
            }
          });
        } else if ("filter0" in _arg) {
          plotAppApi.dispatch({
            type: "filter_replace",
            filter0: _arg.filter0
          });
        } else if (hierClusterApi) {
          plotAppApi.dispatch({
            type: "plot_edit",
            id: hierClusterApi.id,
            config: _arg
          });
        }
      },
      triggerAbort: (_) => plotAppApi.triggerAbort(_)
    };
    return api;
  } catch (e) {
    throw e;
  }
}
export {
  init
};
//# sourceMappingURL=geneExpClustering-FUNS6D2P.js.map
