import {
  loadstudycohort
} from "./chunk-ZTYNN6G5.js";
import {
  childCorsMessage,
  parentCorsMessage
} from "./chunk-PRZWSBMA.js";
import {
  urlmap_default
} from "./chunk-WKNI3HRQ.js";
import {
  block_init_default
} from "./chunk-67DBIM6H.js";
import {
  first_genetrack_tolist,
  sayerror,
  tkt
} from "./chunk-SA7APTJR.js";
import {
  string2pos
} from "./chunk-HJ6L54YS.js";
import {
  dofetch,
  dofetch2,
  dofetch3,
  getSavedToken
} from "./chunk-7EMWHCVW.js";
import {
  copyMerge
} from "./chunk-M3J4MINX.js";

// src/app.mdsjson.js
async function init_mdsjson(file_str, url_str) {
  let json_files = [], json_urls = [];
  if (file_str && file_str.includes(",")) json_files = file_str.split(",");
  else if (file_str) json_files.push(file_str);
  else if (url_str && url_str.includes(",")) json_urls = url_str.split(",");
  else if (url_str) json_urls.push(url_str);
  const tklst = [];
  if (json_files.length) {
    const json_url = void 0;
    for (const json_file of json_files) {
      tklst.push(await tklst_pipeline(json_file, json_url));
    }
  } else if (json_urls.length) {
    const json_file = void 0;
    for (const json_url of json_urls) {
      tklst.push(await tklst_pipeline(json_file, json_url));
    }
  }
  return tklst;
}
async function tklst_pipeline(json_file, json_url) {
  const obj = await mdsjson_parse(json_file, json_url);
  validate_mdsjson(obj);
  const tk = get_json_tk(obj);
  return tk;
}
async function mdsjson_parse(json_file, json_url) {
  if (json_file !== void 0 && json_file == "") throw ".jsonfile missing";
  if (json_url !== void 0 && json_url == "") throw ".jsonurl missing";
  let tmp;
  if (json_file !== void 0) tmp = await dofetch("textfile", { file: json_file });
  else if (json_url !== void 0) tmp = await dofetch("urltextfile", { url: json_url });
  if (tmp.error) {
    throw tmp.error;
  }
  return JSON.parse(tmp.text);
}
function validate_mdsjson(obj) {
  if (!obj) throw "file is missing";
  if (!obj.type) throw "dataset type is missing";
  const svcnvfile = obj.svcnvfile || obj.svcnvurl;
  const vcffile = obj.vcffile || obj.vcfurl;
  if (!svcnvfile && !vcffile) throw "vcf or cnv file/url is required";
  if (Object.keys(obj).filter((x) => x.includes("expression")).length) {
    if (!obj.expressionfile && !obj.expressionurl) throw "expression file/url is missing";
  }
  if (Object.keys(obj).filter((x) => x.includes("rnabam")).length) {
    if (!obj.rnabamfile && !obj.rnabamurl) throw "rnabam file/url is missing";
  }
  if (obj.sampleset) {
    for (const sample of obj.sampleset) {
      if (obj.sampleset.length != 1 && !sample.name) throw "sampleset name is missing";
      if (!sample.samples) throw "sampleset samples[] is missing";
    }
  }
  if (obj.sample2assaytrack) {
    for (const [sample, assaylst] of Object.entries(obj.sample2assaytrack)) {
      if (!assaylst.length) throw "assay[] missing for " + sample;
      for (const assay of assaylst) {
        if (!assay.name) throw "assay name is missing for " + sample;
        if (!assay.type) throw "assay type is missing for " + sample;
      }
    }
  }
  if (obj.groupsamplebyattr) {
    if (!obj.groupsamplebyattr.attrlst) return ".attrlst[] missing from groupsamplebyattr";
    if (obj.groupsamplebyattr.attrlst.length == 0) return "groupsamplebyattr.attrlst[] empty array";
    for (const attr of obj.groupsamplebyattr.attrlst) {
      if (!attr.k) return "k missing from one of groupsamplebyattr.attrlst[]";
    }
    if (obj.groupsamplebyattr.sortgroupby) {
      if (!obj.groupsamplebyattr.sortgroupby.key) return ".key missing from .sortgroupby";
      if (!obj.groupsamplebyattr.sortgroupby.order) return ".order[] missing from .sortgroupby";
      if (!Array.isArray(obj.groupsamplebyattr.sortgroupby.order)) return ".order must be an array";
    }
    if (!obj.groupsamplebyattr.attrnamespacer) obj.groupsamplebyattr.attrnamespacer = ", ";
  }
  if (obj.fixedgeneexpression) {
    for (const gene of obj.fixedgeneexpression) {
      if (!gene.gene) throw "gene missing in fixedgeneexpression array";
    }
  }
  if (obj.vcf) {
    if (!obj.vcf.hiddenclass) throw "hiddenclasses[] missing from .vcf";
  }
}
function get_json_tk(tkobj) {
  const track = {
    type: tkobj.type,
    name: tkobj.name
  };
  if (tkobj.isdense == "true" || tkobj.isdense == true || tkobj.isfull === false) track.isdense = true;
  else if (tkobj.isfull) track.isfull = true;
  if (tkobj.svcnvfile) track.file = tkobj.svcnvfile;
  else if (tkobj.svcnvurl) track.url = tkobj.svcnvurl;
  if (Object.keys(tkobj).filter((x) => x.includes("expression")).length) {
    track.checkexpressionrank = {
      file: tkobj.expressionfile,
      url: tkobj.expressionurl
    };
  }
  if (Object.keys(tkobj).filter((x) => x.includes("vcf")).length) {
    track.checkvcf = {
      file: tkobj.vcffile,
      url: tkobj.vcfurl
    };
  }
  if (tkobj.vcf) {
    if (tkobj.vcf.hiddenclass) {
      track.vcf = [];
      track.vcf.hiddenclass = tkobj.vcf.hiddenclass;
    }
  }
  if (Object.keys(tkobj).filter((x) => x.includes("rnabam")).length) {
    track.checkrnabam = {
      file: tkobj.rnabamfile,
      url: tkobj.rnabamurl
    };
  }
  if (tkobj.sampleset) {
    track.sampleset = tkobj.sampleset;
  }
  if (tkobj.sample2assaytrack) {
    track.sample2assaytrack = tkobj.sample2assaytrack;
  }
  if (tkobj.groupsamplebyattr) {
    track.groupsamplebyattr = tkobj.groupsamplebyattr;
  }
  track.fixedgeneexpression = tkobj.fixedgeneexpression;
  track.getallsamples = tkobj.getallsamples;
  track.valueCutoff = tkobj.cnvValueCutoff !== void 0 ? tkobj.cnvValueCutoff : void 0;
  track.bplengthUpperLimit = tkobj.cnvLengthUpperLimit !== void 0 ? tkobj.cnvLengthUpperLimit : void 0;
  track.segmeanValueCutoff = tkobj.segmeanValueCutoff !== void 0 ? tkobj.segmeanValueCutoff : void 0;
  track.lohLengthUpperLimit = tkobj.lohLengthUpperLimit !== void 0 ? tkobj.lohLengthUpperLimit : void 0;
  track.multihidelabel_vcf = tkobj.multihidelabel_vcf !== void 0 ? tkobj.multihidelabel_vcf : void 0;
  track.multihidelabel_fusion = tkobj.multihidelabel_fusion !== void 0 ? tkobj.multihidelabel_fusion : void 0;
  track.multihidelabel_sv = tkobj.multihidelabel_sv !== void 0 ? tkobj.multihidelabel_sv : void 0;
  track.legend_vorigin = tkobj.legend_vorigin;
  return track;
}
async function get_scatterplot_data(json_file, json_url) {
  let data = {};
  const obj = await mdsjson_parse(json_file, json_url);
  data.mdssamplescatterplot = obj;
  return data;
}

// gdc/launch.ts
async function mayLaunchGdcPlotFromRunpp(arg, app) {
  if (arg.geneSearch4GDCmds3) {
    const _ = await import("./lollipop-LQCQBTSX.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcGb) {
    const _ = await import("./gb-VCJFV63W.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcMatrix) {
    const _ = await import("./oncomatrix-ZILACPPI.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcHierCluster) {
    const _ = await import("./geneExpClustering-FUNS6D2P.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcMaf) {
    const _ = await import("./maf-U237OWZ3.js");
    return await _.gdcMAFui(arg, app.holder0);
  }
  if (arg.launchGdcGrin2) {
    const _ = await import("./grin2-7AOJP5QJ.js");
    return await _.gdcGRIN2ui(arg, app.holder0);
  }
  if (arg.launchGdcScRNAseq) {
    const _ = await import("./singlecell-BGJZB7MF.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcScApp) {
    const _ = await import("./sc-JIDT4W4K.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcCorrelation) {
    const _ = await import("./correlation-AOSSSSL3.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.launchGdcDE) {
    const _ = await import("./DE-CCA5SBJG.js");
    return await _.init(arg, app.holder0, app.genomes);
  }
  if (arg.gdcbamslice) {
    const _ = await import("./bam-QBO22VQB.js");
    arg.gdcbamslice.filter0 = arg.filter0;
    return await _.bamsliceui(arg.gdcbamslice, app.holder0, app.genomes);
  }
}
async function mayLaunchGdcPlotFromUrlparam(urlp, arg) {
  if (urlp.has("gdcbamslice")) {
    const _ = await import("./bam-QBO22VQB.js");
    _.bamsliceui(
      {
        debugmode: arg.debugmode,
        stream2download: urlp.has("stream2download")
        // for testing only, launch the app in "download mode", will not visualize
      },
      arg.holder,
      arg.genomes
    );
    return true;
  }
  if (urlp.has("gdcmaf")) {
    const _ = await import("./maf-U237OWZ3.js");
    const p = {
      debugmode: arg.debugmode
    };
    if (urlp.has("filter0")) p.filter0 = urlp.get("filter0");
    _.gdcMAFui(p, arg.holder);
    return true;
  }
  if (urlp.has("gdcgrin2")) {
    const _ = await import("./grin2-7AOJP5QJ.js");
    const p = {
      debugmode: arg.debugmode
    };
    if (urlp.has("filter0")) p.filter0 = urlp.get("filter0");
    _.gdcGRIN2ui(p, arg.holder);
    return true;
  }
  if (urlp.has("gdccorrelation")) {
    const _ = await import("./correlation-AOSSSSL3.js");
    const p = {
      debugmode: arg.debugmode
    };
    if (urlp.has("filter0")) p.filter0 = urlp.get("filter0");
    _.init(p, arg.holder, arg.genomes);
    return true;
  }
}

// src/app.parseurl.js
async function parse(arg) {
  const urlp = urlmap_default();
  const features = JSON.parse(sessionStorage.getItem("optionalFeatures"));
  if (urlp.has("appcard")) {
    const ad = await import("./adSandbox-R2QP74P7.js");
    const cardJsonFile = urlp.get("appcard");
    const example = urlp.get("example");
    const re = await dofetch2("/cards/index.json");
    arg.app.drawer.opts.genomes = arg.genomes;
    arg.app.drawer.opts.fromApp = true;
    arg.app.drawer.opts.app = {
      cardsPath: "cards"
    };
    const element = re.elements.findIndex(
      (t) => t.sandboxJson == cardJsonFile || t.sandboxHtml == cardJsonFile || t.name.toUpperCase().includes(cardJsonFile.toUpperCase())
    );
    if (re.elements[element]?.configFeature) {
      if (!features[re.elements[element].configFeature]) {
        sayerror(arg.holder, `This track or app is not enabled on this site.`);
        return;
      }
    }
    if (example) {
      arg.app.drawer.opts.example = example;
    }
    if (element <= 0) {
      const nestedCards = [...re.elements.filter((e) => e.type == "nestedCard")];
      let element2, c;
      nestedCards.findIndex((t) => {
        for (const [i, child] of t.children.entries()) {
          if (child.sandboxJson == cardJsonFile || child.sandboxHtml == cardJsonFile || child.name.toUpperCase().includes(cardJsonFile.toUpperCase())) {
            element2 = t;
            c = i;
          }
        }
      });
      if (!element2) {
        sayerror(arg.holder, `Invalid app card.`);
        return;
      }
      ad.openSandbox(element2.children[c], arg.app.drawer.opts);
    } else {
      ad.openSandbox(re.elements[element], arg.app.drawer.opts);
    }
    return;
  }
  if (await mayLaunchGdcPlotFromUrlparam(urlp, arg)) return;
  if (urlp.has("termdb")) {
    const value = urlp.get("termdb");
    const state = typeof value === "string" ? JSON.parse(value) : value;
    const opts = {
      holder: arg.holder,
      state: copyMerge(state, arg.state || {})
    };
    const _ = await import("./app-AIIN4WDE.js");
    const subapp = _.appInit(opts);
    return subapp;
  }
  if (urlp.has("massnative")) {
    const value = urlp.get("massnative");
    const [genomename, dslabel] = value.split(",");
    if (!genomename || !dslabel) throw 'value is not "genome,dslabel"';
    const opts = {
      holder: arg.holder,
      genome: arg.genomes[genomename],
      state: copyMerge(
        {
          genome: genomename,
          dslabel
        },
        arg.state || {}
      ),
      pkgver: arg.app.pkgver,
      launchDate: arg.app.launchDate
    };
    if (!opts.genome) throw "invalid genome";
    childCorsMessage(opts);
    const _ = await import("./app-FJT5VXMF.js");
    const subapp = await _.appInit(opts);
    return subapp;
  }
  if (urlp.has("mass")) {
    const value = urlp.get("mass");
    const state = typeof value === "string" ? JSON.parse(value) : value;
    const opts = {
      debug: arg.app.debugmode,
      holder: arg.holder,
      state: copyMerge(state, arg.state || {}),
      pkgver: arg.app.pkgver,
      launchDate: arg.app.launchDate
    };
    if (state.genome) {
      opts.genome = arg.genomes[state.genome];
    } else if (state?.vocab?.genome) {
      opts.genome = arg.genomes[state.vocab.genome];
    }
    childCorsMessage(opts);
    const _ = await import("./app-FJT5VXMF.js");
    const subapp = await _.appInit(opts);
    return subapp;
  }
  if (urlp.has("mass-session-file") || urlp.has("mass-session-url")) {
    let opts;
    if (urlp.has("mass-session-file")) {
      const file = urlp.get("mass-session-file");
      const d = await dofetch3(`/textfile`, {
        method: "POST",
        body: JSON.stringify({ file })
      });
      if (typeof d != "object") throw "data not object";
      if (d.error) throw d.error;
      if (!d.text) throw "data.text missing";
      const state = JSON.parse(d.text);
      if (features.overrideEmbedderHostInMassSession) {
        state.embedder.host = features.overrideEmbedderHostInMassSession;
        state.embedder.origin = "http://" + features.overrideEmbedderHostInMassSession;
        state.embedder.href = `http://${features.overrideEmbedderHostInMassSession}/`;
      }
      if (state.embedder?.origin && state.embedder.origin != window.location.origin) {
        parentCorsMessage({ state });
        return;
      }
      opts = {
        debug: arg.app.debugmode,
        holder: arg.holder,
        state,
        genome: arg.genomes[state.vocab.genome],
        pkgver: arg.app.pkgver,
        launchDate: arg.app.launchDate
      };
    } else if (urlp.has("mass-session-url")) {
      const url = urlp.get("mass-session-url");
      const d = await dofetch3("/urltextfile", {
        method: "POST",
        body: JSON.stringify({ url })
      });
      if (typeof d != "object") throw "data not object";
      if (d.error) throw d.error;
      if (!d.text) throw "data.text missing";
      const state = JSON.parse(d.text);
      if (state.embedder?.origin && state.embedder.origin != window.location.origin) {
        parentCorsMessage({ state });
        return;
      }
      opts = {
        debug: arg.app.debugmode,
        holder: arg.holder,
        state: copyMerge(state, arg.state || {}),
        genome: arg.genomes[state.vocab.genome],
        pkgver: arg.app.pkgver,
        launchDate: arg.app.launchDate
      };
    }
    const _ = await import("./app-FJT5VXMF.js");
    const subapp = _.appInit(opts);
    return subapp;
  }
  if (urlp.has("mass-session-id")) {
    const id = urlp.get("mass-session-id");
    const src = urlp.get("src");
    let res;
    if (src == "browser") {
      const json = localStorage.getItem("savedMassSessions");
      const savedSessions = JSON.parse(json);
      res = { state: savedSessions[id] };
    } else {
      const fetchOpts = { headers: {}, body: { id } };
      if (src == "cred") {
        const dslabel = urlp.get("dslabel");
        const route = urlp.get("route");
        fetchOpts.body.dslabel = dslabel;
        fetchOpts.body.route = route;
        fetchOpts.body.route = route;
        const jwt = getSavedToken(dslabel, route);
        if (jwt) fetchOpts.headers.authorization = `Bearer ${btoa(jwt)}`;
      }
      res = await dofetch3(`/massSession`, fetchOpts);
      if (res.error) throw res.error;
    }
    const embedder = res.state?.embedder;
    if (embedder?.origin && embedder.origin != window.location.origin) {
      parentCorsMessage(res);
      return;
    }
    const opts = {
      debug: arg.app.debugmode,
      holder: arg.holder,
      state: copyMerge(res.state, arg.state || {}),
      genome: arg.genomes[res.state.vocab.genome],
      sessionDaysLeft: res.sessionDaysLeft,
      sessionId: id,
      pkgver: arg.app.pkgver,
      launchDate: arg.app.launchDate
    };
    const _ = await import("./app-FJT5VXMF.js");
    const subapp = _.appInit(opts);
    return subapp;
  }
  if (urlp.has("genome") && arg.selectgenome) {
    const n = urlp.get("genome");
    const genome_options = [...arg.selectgenome.node().childNodes];
    const selectedIndex = genome_options.findIndex((d) => d.value == n);
    if (selectedIndex == -1) {
      sayerror(
        arg.holder,
        `Invalid genome: ${n}. Please provide an available genome from this list: ${genome_options.map((d) => d.value).join(", ").replace(/,(?=[^,]*$)/, ", or")}`
      );
      return;
    }
    arg.selectgenome.node().selectedIndex = selectedIndex;
    arg.selectgenome.node().dispatchEvent(new Event("change"));
  }
  if (urlp.has("hicfile") || urlp.has("hicurl")) {
    let file, url, name;
    if (urlp.has("hicfile")) {
      file = urlp.get("hicfile");
      name = file.split("/").pop();
    } else {
      url = urlp.get("hicurl");
      name = url.split("/").pop();
    }
    const gn = urlp.get("genome");
    if (!gn) throw "genome is required for hic";
    const genome = arg.genomes[gn];
    if (!genome) throw "invalid genome";
    const hic = {
      genome,
      file,
      url,
      name,
      //.basename(file || url),
      hostURL: arg.hostURL,
      enzyme: urlp.get("enzyme"),
      holder: arg.holder
    };
    const _ = await import("./HicApp-BBD2YOMT.js");
    await _.hicInit(hic);
    return;
  }
  if (urlp.has("singlecell")) {
    if (!urlp.has("genome")) throw '"genome" is required for "singlecell"';
    const genomename = urlp.get("genome");
    const genomeobj = arg.genomes[genomename];
    if (!genomeobj) throw "invalid genome: " + genomename;
    const _ = await import("./singlecell-RO3BL5OO.js");
    _.init(
      {
        genome: genomeobj,
        jsonfile: urlp.get("singlecell")
      },
      arg.holder
    );
    return;
  }
  if (urlp.has("mavbfile")) {
    if (!urlp.has("genome")) throw '"genome" is required for "mavb"';
    const genomename = urlp.get("genome");
    const genome = arg.genomes[genomename];
    if (!genome) throw "invalid genome: " + genomename;
    const _ = await import("./mavb-SQDA3B2B.js");
    _.mavbparseinput(
      {
        genome,
        hostURL: arg.hostURL,
        file: urlp.get("mavbfile")
      },
      () => {
      },
      arg.holder,
      arg.jwt
    );
    return;
  }
  if (urlp.has("mavburl")) {
    if (!urlp.has("genome")) throw '"genome" is required for "mavb"';
    const genomename = urlp.get("genome");
    const genome = arg.genomes[genomename];
    if (!genome) throw "invalid genome: " + genomename;
    const _ = await import("./mavb-SQDA3B2B.js");
    _.mavbparseinput(
      {
        genome,
        hostURL: arg.hostURL,
        url: urlp.get("mavburl")
      },
      () => {
      },
      arg.holder,
      arg.jwt
    );
    return;
  }
  if (urlp.has("scatterplot")) {
    if (!urlp.has("genome")) throw '"genome" is required for "scatterplot"';
    const genomename = urlp.get("genome");
    const genome = arg.genomes[genomename];
    if (!genome) throw "invalid genome: " + genomename;
    let plot_data;
    if (urlp.has("mdsjson") || urlp.has("mdsjsonurl")) {
      const url_str = urlp.get("mdsjsonurl");
      const file_str = urlp.get("mdsjson");
      plot_data = await get_scatterplot_data(file_str, url_str);
    }
    if (urlp.has("tsnejson")) {
      const file_str = urlp.get("tsnejson");
      const data = await dofetch("textfile", { file: file_str });
      if (data.error) throw data.error;
      else if (data.text) {
        plot_data = {
          mdssamplescatterplot: {
            analysisdata: JSON.parse(data.text)
          }
        };
      }
    }
    plot_data.mdssamplescatterplot.genome = genome;
    const _ = await import("./mds.samplescatterplot-Y5V73GOY.js");
    _.init(plot_data.mdssamplescatterplot, arg.holder, false);
    return;
  }
  if (urlp.has("block")) {
    if (!urlp.has("genome")) throw "missing genome for block";
    const genomename = urlp.get("genome");
    const genomeobj = arg.genomes[genomename];
    if (!genomeobj) throw "invalid genome: " + genomename;
    const par = {
      nobox: 1,
      hostURL: arg.hostURL,
      jwt: arg.jwt,
      holder: arg.holder,
      genome: genomeobj,
      dogtag: genomename,
      debugmode: arg.debugmode
    };
    let position = null;
    let rglst = null;
    if (urlp.has("position")) {
      const lst = urlp.get("position").split(";");
      if (lst[0]) {
        const tmp = lst[0].split(/[:-]/);
        const chr = tmp[0];
        const start = Number.parseInt(tmp[1]);
        const stop = Number.parseInt(tmp[2]);
        if (!chr) throw "chr missing";
        if (Number.isNaN(start) || Number.isNaN(stop)) throw "Invalid start/stop value in position";
        position = { chr, start, stop };
      }
      const subpanels = [];
      for (let i = 1; i < lst.length; i++) {
        if (!lst[i]) continue;
        const tmp = lst[i].split(/[:-]/);
        const chr = tmp[0];
        const start = Number.parseInt(tmp[1]);
        const stop = Number.parseInt(tmp[2]);
        if (!chr) throw "subpanel chr missing";
        if (Number.isNaN(start) || Number.isNaN(stop)) throw "Invalid start/stop value in subpanel position";
        subpanels.push({
          chr,
          start,
          stop,
          width: 600,
          leftborder: "rgba(200,0,0,.1)",
          leftpad: 5
        });
      }
      if (subpanels.length) {
        par.subpanels = subpanels;
      }
    }
    if (urlp.has("regions")) {
      rglst = [];
      for (const s of urlp.get("regions").split(",")) {
        const l = s.split(/[:-]/);
        const chr = l[0];
        const start = Number.parseInt(l[1]);
        const stop = Number.parseInt(l[2]);
        if (Number.isNaN(start) || Number.isNaN(stop)) throw "Invalid start/stop value in regions";
        rglst.push({ chr: l[0], start, stop });
      }
    }
    if (!position && !rglst) {
      if (genomeobj.defaultcoord) {
        position = {
          chr: genomeobj.defaultcoord.chr,
          start: genomeobj.defaultcoord.start,
          stop: genomeobj.defaultcoord.stop
        };
      }
    }
    if (position) {
      par.chr = position.chr;
      par.start = position.start;
      par.stop = position.stop;
    } else if (rglst) {
      par.rglst = rglst;
    }
    if (urlp.has("hlregion")) {
      const lst = [];
      for (const t of urlp.get("hlregion").split(",")) {
        const pos = string2pos(t, genomeobj, true);
        if (pos) lst.push(pos);
      }
      if (lst.length) par.hlregions = lst;
    }
    par.datasetqueries = may_get_officialmds(urlp);
    par.tklst = await get_tklst(urlp, genomeobj);
    first_genetrack_tolist(arg.genomes[genomename], par.tklst);
    mayAddBedjfilterbyname(urlp, par.tklst);
    const b = await import("./block-TTN2IQAH.js");
    new b.Block(par);
    return;
  }
  if (urlp.has("gene")) {
    const str = urlp.get("gene");
    if (str.length == 0) throw "zero length query string";
    const par = {
      hostURL: arg.hostURL,
      query: str,
      holder: arg.holder,
      variantPageCall_snv: arg.variantPageCall_snv,
      samplecart: arg.samplecart,
      debugmode: arg.debugmode
    };
    {
      let genomename;
      for (let n in arg.genomes) {
        if (arg.genomes[n].isdefault) {
          genomename = n;
          break;
        }
      }
      if (urlp.has("genome")) {
        genomename = urlp.get("genome");
      }
      if (!genomename) throw "No genome, and none set as default";
      par.genome = arg.genomes[genomename];
      if (!par.genome) throw "invalid genome: " + genomename;
    }
    let ds = null;
    if (urlp.has("dataset")) {
      par.dataset = urlp.get("dataset").split(",");
    }
    if (urlp.has("hlaachange")) {
      par.hlaachange = /* @__PURE__ */ new Map();
      for (const s of urlp.get("hlaachange").split(",")) {
        par.hlaachange.set(s, false);
      }
    }
    if (urlp.has("hlregion")) {
      const lst = [];
      for (const t of urlp.get("hlregion").split(",")) {
        const pos = string2pos(t, par.genome, true);
        if (pos) lst.push(pos);
      }
      if (lst.length) par.hlregions = lst;
    }
    par.tklst = await get_tklst(urlp, par.genome);
    mayAddBedjfilterbyname(urlp, par.tklst);
    par.datasetqueries = may_get_officialmds(urlp);
    await block_init_default(par);
    return;
  }
  if (urlp.has("disco")) {
    const genomeName = urlp.get("genome");
    const genome = arg.genomes[genomeName];
    if (!genome) throw "genome missing";
    const dslabel = urlp.get("dslabel");
    if (!dslabel) throw "dslabel missing";
    const sample_id = urlp.get("sample");
    if (!sample_id) throw "sample_id missing";
    const vocabApi = (await import("./vocabulary-D3W44IWE.js")).vocabInit({ state: { genome: genomeName, dslabel } });
    const termdbConfig = await vocabApi.getTermdbConfig();
    await (await import("./plot.disco-OUE4RFHL.js")).default(termdbConfig, dslabel, { sample_id }, arg.holder, genome);
    return;
  }
  if (urlp.has("study")) {
    const v = urlp.get("study");
    if (v != "") {
      loadstudycohort(
        arg.genomes,
        v,
        arg.holder,
        arg.hostURL,
        void 0,
        // jwt
        false,
        // no show
        arg.app || {
          debugmode: arg.debugmode,
          instanceTracker: arg.instanceTracker || {},
          callbacks: arg.callbacks || {}
        }
      );
    }
  }
}
function may_get_officialmds(urlp) {
  if (!urlp.has("mds")) return;
  const tmp = urlp.get("mds").split(",");
  if (tmp[0] && tmp[1]) {
    const dataset = { dataset: tmp[0], querykey: tmp[1] };
    if (urlp.has("sample")) {
      dataset.singlesample = { name: urlp.get("sample") };
      dataset.getsampletrackquickfix = true;
    }
    return [dataset];
  }
  return;
}
async function get_tklst(urlp, genomeobj) {
  const tklst = [];
  for (const [key, value] of urlp) {
    const tks = await mayGetTkobj(key, value, urlp, genomeobj);
    if (!tks) continue;
    if (Array.isArray(tks)) tklst.push(...tks);
    else tklst.push(tks);
  }
  for (const t of tklst) {
    if (t.type == "mds3" && t.dslabel) continue;
    t.iscustom = true;
  }
  if (urlp.has("isdense")) {
    tklst.filter((t) => t.type == tkt.mdssvcnv).forEach((t) => {
      t.isdense = true;
      t.isfull = false;
    });
  }
  if (urlp.has("sample")) {
    tklst.filter((t) => t.type == tkt.mdssvcnv).forEach((t) => {
      t.singlesample = { name: urlp.get("sample") };
      t.getsampletrackquickfix = true;
    });
  }
  return tklst;
}
async function mayGetTkobj(key, value, urlp, genomeobj) {
  if (key == "mds3") {
    const lst = value.split(",");
    const tks = [];
    for (const n of lst) {
      const tk = {
        type: tkt.mds3,
        dslabel: n
      };
      if (urlp.has("token")) tk.token = urlp.get("token");
      if (urlp.has("filterobj")) tk.filterObj = urlp.get("filterobj");
      if (urlp.has("cnvonly")) tk.hardcodeCnvOnly = true;
      if (urlp.has("snvindelonly")) tk.snvIndelOnly = true;
      tks.push(tk);
    }
    return tks;
  }
  if (key == "mds3bcffile") {
    const [tkname, bcffile] = value.split(",");
    let tk;
    if (tkname && bcffile) {
      tk = {
        type: tkt.mds3,
        name: tkname,
        bcf: { file: bcffile }
      };
    }
    return tk;
  }
  if (key == "mds3bcfurl") {
    const [tkname, url, indexURL] = value.split(",");
    let tk;
    if (tkname && url) {
      tk = {
        type: tkt.mds3,
        name: tkname,
        bcf: { url, indexURL }
      };
    }
    return tk;
  }
  if (key == "arcfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.hicstraw,
          name: lst[i],
          bedfile: lst[i + 1],
          mode_hm: false,
          mode_arc: true
        });
      }
    }
    return tks;
  }
  if (key == "mdsjson" || key == "mdsjsonurl") {
    let url_str, file_str;
    if (key == "mdsjson") file_str = value;
    else url_str = value;
    return await init_mdsjson(file_str, url_str);
  }
  if (key == "tkjsonfile") {
    const re = await dofetch("textfile", { file: value });
    if (re.error) throw re.error;
    if (!re.text) throw ".text missing";
    const lst = JSON.parse(re.text);
    const tks = [];
    for (const i of lst) {
      if (i.isfacet) {
        if (!genomeobj.tkset) genomeobj.tkset = [];
        if (!i.tracks) throw ".tracks[] missing from a facet table";
        if (!Array.isArray(i.tracks)) throw ".tracks[] not an array from a facet table";
        i.tklst = i.tracks;
        delete i.tracks;
        for (const t of i.tklst) {
          if (!t.assay) throw ".assay missing from a facet track";
          if (!t.sample) throw ".sample missing from a facet track";
          t.tkid = Math.random().toString();
        }
        genomeobj.tkset.push(i);
      } else {
        tks.push(i);
      }
    }
    return tks;
  }
  if (key == "bamfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bam,
          name: lst[i],
          file: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "bamurl") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bam,
          name: lst[i],
          url: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "bedjfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bedj,
          name: lst[i],
          file: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "bedjurl") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bedj,
          name: lst[i],
          url: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "hictkfile" || key == "hictkurl") {
    const isfile = key == "hictkfile";
    const lst = value.split(",");
    const norm = urlp.has("hictknorm") ? urlp.get("hictknorm").split(",") : null;
    const tks = [];
    for (let i = 0; i < lst.length; i += 3) {
      if (lst[i] && lst[i + 1] && lst[i + 2]) {
        const t = {
          type: tkt.hicstraw,
          name: lst[i],
          enzyme: lst[i + 1],
          normalizationmethod: norm ? norm[i / 3] : null
        };
        if (isfile) {
          t.file = lst[i + 2];
        } else {
          t.url = lst[i + 2];
        }
        tks.push(t);
      }
    }
    return tks;
  }
  if (key == "ldfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.ld,
          name: lst[i],
          file: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "bigwigfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bigwig,
          name: lst[i],
          file: lst[i + 1],
          scale: { auto: 1 }
        });
      }
    }
    return tks;
  }
  if (key == "bigwigurl") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.bigwig,
          name: lst[i],
          url: lst[i + 1],
          scale: { auto: 1 }
        });
      }
    }
    return tks;
  }
  if (key == "junctionfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.junction,
          name: lst[i],
          tracks: [
            {
              file: lst[i + 1]
            }
          ]
        });
      }
    }
    return tks;
  }
  if (key == "junctionurl") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.junction,
          name: lst[i],
          tracks: [
            {
              url: lst[i + 1]
            }
          ]
        });
      }
    }
    return tks;
  }
  if (key == "aicheckfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: "aicheck",
          name: lst[i],
          file: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "bampilefile") {
    const lst = value.split(",");
    let links = null;
    if (urlp.has("bampilelink")) {
      links = urlp.get("bampilelink").split(",").map(decodeURIComponent);
    }
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        const tk = {
          type: tkt.bampile,
          name: lst[i],
          file: lst[i + 1]
        };
        if (links && links[i / 2]) {
          tk.link = links[i / 2];
        }
        tks.push(tk);
      }
    }
    return tks;
  }
  if (key == "svcnvfpkmurl") {
    const lst = value.split(",");
    const name = lst[0];
    const type2url = {};
    for (let i = 1; i < lst.length; i += 2) {
      type2url[lst[i]] = lst[i + 1];
    }
    let tk;
    if (type2url.svcnv || type2url.vcf) {
      tk = {
        type: tkt.mdssvcnv,
        name
      };
      if (type2url.svcnv) {
        tk.url = type2url.svcnv;
      }
      if (type2url.vcf) {
        tk.checkvcf = {
          url: type2url.vcf,
          indexURL: type2url.vcfindex
        };
      }
      if (type2url.fpkm) {
        tk.checkexpressionrank = {
          datatype: "FPKM",
          url: type2url.fpkm,
          indexURL: type2url.fpkmindex
        };
      }
    }
    return tk;
  }
  if (key == "svcnvfpkmfile") {
    const lst = value.split(",");
    const name = lst[0];
    const type2file = {};
    for (let i = 1; i < lst.length; i += 2) {
      type2file[lst[i]] = lst[i + 1];
    }
    let tk;
    if (type2file.svcnv || type2file.vcf) {
      tk = {
        type: tkt.mdssvcnv,
        name
      };
      if (type2file.svcnv) {
        tk.file = type2file.svcnv;
      }
      if (type2file.vcf) {
        tk.checkvcf = {
          file: type2file.vcf
        };
      }
      if (type2file.fpkm) {
        tk.checkexpressionrank = {
          datatype: "FPKM",
          file: type2file.fpkm
        };
      }
    }
    return tk;
  }
  if (key == "mdsjunctionfile") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: "mdsjunction",
          name: lst[i],
          file: lst[i + 1]
        });
      }
    }
    return tks;
  }
  if (key == "junctionmatrix") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: "mdsjunction",
          name: lst[i],
          file2: lst[i + 1]
          // quick fix to support new file type
        });
      }
    }
    return tks;
  }
  if (key == "junctionrnapeg") {
    const lst = value.split(",");
    const tks = [];
    for (let i = 0; i < lst.length; i += 2) {
      if (lst[i] && lst[i + 1]) {
        tks.push({
          type: tkt.junction,
          name: lst[i],
          tracks: [{ rnapegfile: lst[i + 1] }]
        });
      }
    }
    return tks;
  }
}
function mayAddBedjfilterbyname(urlp, tklst) {
  if (urlp.has("bedjfilterbyname")) {
    for (const t of tklst) {
      if (t.type == "bedj") t.filterByName = urlp.get("bedjfilterbyname");
    }
  }
}

export {
  init_mdsjson,
  mayLaunchGdcPlotFromRunpp,
  parse,
  get_tklst
};
//# sourceMappingURL=chunk-IW57W7EQ.js.map
