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 {
  dofetch3
} from "./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 {
  select_default
} from "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// gdc/oncomatrix.js
var gdcGenome = "hg38";
var gdcDslabel = "GDC";
async function init(arg, holder, genomes) {
  const toolGenome = arg.genome || gdcGenome;
  const toolDslabel = arg.dslabel || gdcDslabel;
  const genome = genomes[toolGenome];
  try {
    if (!genome) throw toolGenome + " missing";
    const settings = arg.settings || {};
    if (typeof settings != "object") throw "arg.settings{} not object";
    if (!settings.matrix) settings.matrix = {};
    if (typeof settings.matrix != "object") throw "arg.settings.matrix{} not object";
    if (!settings.matrix.geneFilter) settings.matrix.geneFilter = "CGC";
    if (!Number.isInteger(settings.matrix.maxGenes)) settings.matrix.maxGenes = 50;
    if (arg.filter0 && typeof arg.filter0 != "object") throw "arg.filter0 not object";
    const vocabApi = await vocabInit({
      state: { vocab: { genome: toolGenome, dslabel: toolDslabel } }
    });
    vocabApi.getTermdbConfig();
    const plotAppApi = await appInit({
      holder: select_default(arg.holder).select(".sja_root_holder"),
      genome,
      state: copyMerge(
        {
          genome: toolGenome,
          dslabel: toolDslabel,
          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: "OncoMatrix",
              settings: {
                maxGenes: settings.matrix.maxGenes,
                geneFilter: settings.matrix.geneFilter
              }
            }
          ]
        },
        arg.state || {}
      ),
      app: arg.opts?.app || {},
      geneset: {
        mode: "geneVariant",
        // consistent mode value as GeneSetEdit
        genome,
        genes: arg.genes,
        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 the top mutated genes in the current cohort...");
        },
        async callback(_genesetCompApi, twlst) {
          if (!_genesetCompApi) return;
          genesetCompApi = _genesetCompApi;
          if (!matrixApi) {
            const plotConfig = plotAppApi.getState().plots.find((p) => p.chartType == "matrix");
            if (plotConfig) matrixApi = plotAppApi.getComponents(`plots.${plotConfig.id}`);
          }
          const termgroups = [
            ...arg.termgroups || [],
            {
              //name: 'Gene Expression',
              lst: twlst
            }
          ];
          if (matrixApi) {
            plotAppApi.dispatch({
              type: "plot_edit",
              id: matrixApi.id,
              config: { termgroups }
            });
          } else {
            plotAppApi.dispatch({
              type: "plot_create",
              config: {
                chartType: "matrix",
                // 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
              }
            });
          }
        }
      },
      recover: {
        undoHtml: "Undo",
        redoHtml: "Redo",
        resetHtml: "Restore",
        hide(state) {
          return state.plots[0]?.chartType != "matrix";
        },
        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;
        }
      },
      matrix: 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;
          },
          // these will display the inputs together in the Genes menu,
          // instead of being rendered outside of the matrix holder
          customInputs: {
            genes: [
              {
                label: `Maximum # Genes`,
                title: "Limit the number of displayed genes",
                type: "number",
                chartType: "matrix",
                settingsKey: "maxGenes",
                callback: async (value) => {
                  for (const key in arg.opts?.app?.callbacks) {
                    if (key.startsWith("preDispatch")) {
                      arg.opts?.app?.callbacks[key]();
                      break;
                    }
                  }
                  const genes = await getGenes(
                    arg,
                    { maxGenes: value, geneFilter: settings.matrix.geneFilter },
                    vocabApi
                  );
                  api.update({
                    termgroups: [{ lst: genes }],
                    settings: {
                      matrix: { maxGenes: value }
                    }
                  });
                }
              }
            ]
          },
          callbacks: {
            "firstRender.gdcMatrix": async (matrixApi2) => {
              matrixApi2.on("firstRender.gdcMatrix", null);
              if (!genesetCompApi) return;
              plotAppApi.dispatch({
                type: "plot_delete",
                id: genesetCompApi.id
              });
              genesetCompApi = void 0;
            }
          }
        },
        arg.opts?.matrix || {}
      )
    });
    let matrixApi, genesetCompApi;
    const api = {
      getState: () => plotAppApi.getState(),
      destroy: () => plotAppApi.destroy(),
      update: async (arg2) => {
        if (!matrixApi) {
          const plotConfig = plotAppApi.getState().plots.find((p) => p.chartType == "matrix");
          if (plotConfig) matrixApi = plotAppApi.getComponents(`plots.${plotConfig.id}`);
        }
        if (arg2.genes) {
          plotAppApi.dispatch({
            type: "plot_edit",
            id: matrixApi.id,
            config: {
              termgroups: [
                {
                  lst: await Promise.all(
                    arg2.genes.map(async (g) => {
                      return await fillTermWrapper(
                        {
                          term: { gene: g.gene, type: "geneVariant", name: g.gene }
                        },
                        vocabApi
                      );
                    })
                  )
                }
              ]
            }
          });
        } else if ("filter0" in arg2) {
          plotAppApi.dispatch({
            type: "filter_replace",
            filter0: arg2.filter0
          });
        } else if (matrixApi) {
          plotAppApi.dispatch({
            type: "plot_edit",
            id: matrixApi.id,
            config: arg2
          });
        }
      },
      triggerAbort: (_) => plotAppApi.triggerAbort(_)
    };
    return api;
  } catch (e) {
    throw e;
  }
}
async function getGenes(arg, settings, vocabApi) {
  const body = {
    genome: gdcGenome,
    dslabel: arg.dslabel || gdcDslabel,
    maxGenes: settings.maxGenes,
    geneFilter: settings.geneFilter
  };
  if (arg.filter0) body.filter0 = arg.filter0;
  const data = await dofetch3("termdb/topMutatedGenes", { body });
  if (data.error) throw data.error;
  if (!data.genes) return;
  return await Promise.all(
    // do tempfix of "data.genes.slice(0,3).map" for faster testing
    data.genes.map(async (i) => {
      return fillTermWrapper({ term: { gene: i.gene, type: "geneVariant" } }, vocabApi);
    })
  );
}
export {
  init
};
//# sourceMappingURL=oncomatrix-ZILACPPI.js.map
