import {
  sample_match_termvaluesetting
} from "./chunk-YZK37YCC.js";
import {
  isDictionaryType
} from "./chunk-NOEAT6CX.js";
import {
  __export
} from "./chunk-HFNDKYVF.js";

// plots/matrix/matrix.data.js
var matrix_data_exports = {};
__export(matrix_data_exports, {
  applyLegendValueFilter: () => applyLegendValueFilter,
  getMatrixRequestOpts: () => getMatrixRequestOpts,
  mayRequireToken: () => mayRequireToken,
  setData: () => setData
});
function mayRequireToken(tokenMessage = "") {
  const message = tokenMessage || this.state.tokenVerificationMessage;
  if (!message && this.state.hasVerifiedToken) {
    this.dom.errdiv.style("display", "none").html();
    this.dom.controls.style("display", this.opts.controls ? "inline-block" : "");
    this.dom.svg.style("display", "");
    return false;
  } else {
    this.dom.errdiv.style("display", "").html(message || "Requires login");
    this.dom.controls.style("display", "none");
    this.dom.svg.style("display", "none");
    return true;
  }
}
function getMatrixRequestOpts(state, config) {
  const terms = [];
  const termgroups = this.chartType == "hierCluster" ? config.termgroups.filter((grp) => grp.type != "hierCluster") : config.termgroups;
  for (const grp of termgroups) {
    terms.push(...getNormalizedTwLstCopy(grp.lst));
  }
  if (config.divideBy) terms.push(normalizeTwForRequest(structuredClone(config.divideBy)));
  const opts = {
    terms,
    filter: state.filter,
    filter0: state.filter0,
    maxGenes: state.config.settings.matrix.maxGenes,
    /*********** quick fix
    when the flag is true, set artificially large number to ensure all genes are sent in one query
    this avoids changing getAnnotatedSampleData()
    additional non-matrix app that calls getAnnotatedSampleData will NEED THE SAME FIX
    */
    termsPerRequest: this.app.vocabApi.termdbConfig.queries?.snvindel?.byisoform?.processTwsInOneQuery ? 1e3 : 1
  };
  if (this.chartType == "hierCluster") {
    opts.isHierCluster = 1;
  }
  return opts;
}
function getNormalizedTwLstCopy(twlst) {
  const lst = [];
  for (const tw of twlst) {
    if (tw.type && tw.constructor.name != "Object") lst.push(tw);
    else lst.push(normalizeTwForRequest(tw));
  }
  lst.forEach(normalizeTwForRequest);
  lst.sort(sortTwLst);
  return lst;
}
function normalizeTwForRequest(_tw) {
  const tw = structuredClone(_tw);
  if (!tw?.term) return;
  delete tw.term.category2samplecount;
  if (isDictionaryType(tw.term.type) && tw.term.type !== "samplelst") delete tw.term.values;
  return tw;
}
function sortTwLst(twa, twb) {
  const a = twa?.$id || twa.term?.id || twa?.term?.name;
  const b = twb?.$id || twb.term?.id || twb?.term?.name;
  return a < b ? -1 : 1;
}
async function setData(_data) {
  const opts = this.currRequestOpts?.matrix || this.getMatrixRequestOpts(this.state, this.config);
  this.numTerms = opts.terms.length;
  opts.loadingDiv = this.chartType != "hierCluster" && this.dom.loadingDiv;
  opts.signal = this.api.getAbortSignal();
  const data = await this.app.vocabApi.getAnnotatedSampleData(opts, _data);
  this.data = data;
  this.origData = structuredClone(this.data);
  this.sampleIdMap = {};
  for (const d of this.data.lst) {
    this.sampleIdMap[d.sample] = d._ref_.label;
  }
}
function applyLegendValueFilter() {
  const self = this;
  if (!self.config.legendValueFilter.lst.length && !self.config.legendGrpFilter.lst.length) return;
  for (const grpFilter of self.config.legendGrpFilter.lst) {
    if (grpFilter.dt) {
      const filteredOutCats = /* @__PURE__ */ new Set();
      for (const oneSampleData of self.origData.lst) {
        for (const annoForOneTerm of Object.values(oneSampleData)) {
          if (annoForOneTerm.values) {
            const newValues = [];
            for (const v of annoForOneTerm.values) {
              if (!(grpFilter.dt.includes(v.dt) && (!grpFilter.origin || v.origin == grpFilter.origin))) {
                newValues.push(v);
              } else {
                filteredOutCats.add(v.class);
              }
            }
            annoForOneTerm.values = newValues;
          }
        }
      }
      grpFilter.filteredOutCats = [...filteredOutCats];
      for (const oneSampleData of Object.values(self.origData.samples)) {
        for (const annoForOneTerm of Object.values(oneSampleData)) {
          if (annoForOneTerm.values)
            annoForOneTerm.values = annoForOneTerm.values.filter(
              (v) => !(grpFilter.dt.includes(v.dt) && (!grpFilter.origin || v.origin == grpFilter.origin))
            );
        }
      }
    }
  }
  const geneVariant$ids = Object.values(self.data.refs.byTermId).filter((v) => v.term?.type == "geneVariant").map((v) => v.$id);
  const data = { samples: {}, lst: [], refs: self.data.refs };
  const onlyHardFilter = structuredClone(self.config.legendValueFilter);
  onlyHardFilter.lst = onlyHardFilter.lst.filter(
    (l) => !l.tvs.legendFilterType || l.tvs.legendFilterType !== "geneVariant_soft"
  );
  for (const row of self.origData.lst) {
    const include = sample_match_termvaluesetting(row, onlyHardFilter, geneVariant$ids);
    if (include || self.chartType == "hierCluster") {
      data.samples[row.sample] = row;
      data.lst.push(row);
    }
  }
  for (const valFilter of self.config.legendValueFilter.lst) {
    if (valFilter.tvs.legendFilterType !== "geneVariant_soft") continue;
    const tvsV = valFilter.tvs.values[0];
    const filteredOutCats = /* @__PURE__ */ new Set();
    for (const oneSampleData of data.lst) {
      for (const annoForOneTerm of Object.values(oneSampleData)) {
        if (annoForOneTerm.values) {
          const newValues = [];
          for (const v of annoForOneTerm.values) {
            if (!(v.dt == tvsV.dt && (!tvsV.origin || v.origin == tvsV.origin) && tvsV.mclasslst.includes(v.class))) {
              newValues.push(v);
            } else {
              filteredOutCats.add(v.class);
            }
          }
          annoForOneTerm.values = newValues;
        }
      }
    }
    valFilter.filteredOutCats = [...filteredOutCats];
    for (const oneSampleData of Object.values(data.samples)) {
      for (const annoForOneTerm of Object.values(oneSampleData)) {
        if (annoForOneTerm.values)
          annoForOneTerm.values = annoForOneTerm.values.filter(
            (v) => !(v.dt == tvsV.dt && (!tvsV.origin || v.origin == tvsV.origin) && tvsV.mclasslst.includes(v.class))
          );
      }
    }
  }
  if (self.chartType !== "hierCluster" && geneVariant$ids.length && self.app.vocabApi.vocab?.dslabel == "GDC")
    remove_empty_sample(data, geneVariant$ids);
  self.data = data;
}
function remove_empty_sample(data) {
  for (const oneSampleData of data.lst) {
    let removeSample = true;
    for (const [key, annoForOneTerm] of Object.entries(oneSampleData)) {
      if (!annoForOneTerm.values) continue;
      const annoType = data.refs.byTermId[key].term.type;
      if (annoType != "geneVariant") continue;
      if (annoForOneTerm.values.length) removeSample = false;
    }
    if (removeSample) {
      data.lst = data.lst.filter((dl) => dl.sample !== oneSampleData.sample);
      delete data.samples[parseInt(oneSampleData.sample)];
    }
  }
  return data;
}

export {
  mayRequireToken,
  getMatrixRequestOpts,
  setData,
  applyLegendValueFilter,
  matrix_data_exports
};
//# sourceMappingURL=chunk-XMLURPEP.js.map
