import {
  first_genetrack_tolist,
  gmmode,
  sayerror
} from "./chunk-SA7APTJR.js";
import {
  dofetch3
} from "./chunk-7EMWHCVW.js";
import {
  codon_stop,
  nt2aa,
  proteinDomainColorScale
} from "./chunk-4UWS5Y3N.js";
import {
  select_default
} from "./chunk-I6Y4O3RR.js";

// common/snp.js
async function string2snp(genome, str) {
  const data = await dofetch3("snp", {
    method: "POST",
    body: JSON.stringify({ byName: true, genome: genome.name, lst: [str] })
  });
  if (data.error) throw data.error;
  if (!data.results || data.results.length == 0) throw str + ": not a SNP";
  for (const i of data.results) {
    const chr = genome.chrlookup[i.chrom.toUpperCase()];
    if (chr && chr.major) {
      return {
        chr: i.chrom,
        start: i.chromStart,
        stop: i.chromEnd
      };
    }
  }
  const r = data.results[0];
  return {
    chr: r.chrom,
    start: r.chromStart,
    stop: r.chromEnd
  };
}

// src/block.init.js
async function block_init_default(arg) {
  if (!arg.holder) throw "No holder for block.init";
  if (!arg.genome) throw "no genome";
  if (arg.holder instanceof Element) arg.holder = select_default(arg.holder);
  if (!arg.tklst) arg.tklst = [];
  if (arg.query) {
    await step1_findgm(arg);
    return;
  }
  if (arg.model && arg.allmodels) {
    await step2_getseq(arg);
    return;
  }
}
async function step1_findgm(arg) {
  const wait = arg.holder.append("p").style("font-size", "2em").style("color", "#858585").text("Searching for " + arg.query + " ...");
  const data = await dofetch3("genelookup", {
    body: { deep: 1, input: arg.query, genome: arg.genome.name }
  });
  if (!data) throw "querying genes: server error";
  if (data.error) throw "error querying genes: " + data.error;
  if (!data.gmlst || data.gmlst.length == 0) {
    if (arg.genome.hasSNP) {
      try {
        const r = await string2snp(arg.genome, arg.query);
        wait.remove();
        const par = {
          genome: arg.genome,
          holder: arg.holder,
          chr: r.chr,
          start: Math.max(0, r.start - 300),
          stop: r.start + 300,
          nobox: true,
          tklst: arg.tklst,
          debugmode: arg.debugmode
        };
        first_genetrack_tolist(arg.genome, par.tklst);
        const b = await import("./block-TTN2IQAH.js");
        const block = new b.Block(par);
        block.addhlregion(r.chr, r.start, r.stop - 1);
      } catch (e) {
        wait.text("Not a gene or SNP: " + arg.query);
      }
    } else {
      wait.text("No match to gene: " + arg.query);
    }
    return;
  }
  wait.remove();
  arg.allmodels = data.gmlst;
  for (const m of arg.allmodels) {
    if (m.isoform.toUpperCase() == (data.found_isoform ? data.found_isoform.toUpperCase() : arg.query.toUpperCase())) {
      arg.model = m;
      await step2_getseq(arg);
      return;
    }
  }
  const defaultisoforms = [];
  for (const m of arg.allmodels) {
    if (!m.isoform) throw "isoform missing from one gene model: " + JSON.stringify(m);
    const n = m.isoform.toUpperCase();
    if (arg.genome.isoformcache.has(n)) {
      let nothas = true;
      for (const m2 of arg.genome.isoformcache.get(n)) {
        if (m2.chr == m.chr && m2.start == m.start && m2.stop == m.stop && m2.strand == m.strand) {
          nothas = false;
          break;
        }
      }
      if (nothas) {
        arg.genome.isoformcache.get(n).push(m);
      }
    } else {
      arg.genome.isoformcache.set(n, [m]);
    }
    if (m.isoform.toUpperCase() == arg.query.toUpperCase()) {
      defaultisoforms.push(m);
      break;
    }
    if (m.isdefault) {
      defaultisoforms.push(m);
    }
  }
  if (defaultisoforms.length == 1) {
    arg.model = defaultisoforms[0];
  } else if (defaultisoforms.length > 1) {
    for (const m of defaultisoforms) {
      if (m.chr == "chrY") {
        continue;
      }
      const chr = arg.genome.chrlookup[m.chr.toUpperCase()];
      if (!chr) {
        continue;
      }
      if (!chr.major) {
        continue;
      }
      arg.model = m;
      break;
    }
    if (!arg.model) {
      arg.model = defaultisoforms[0];
    }
  }
  if (!arg.model) {
    arg.model = arg.allmodels[0];
  }
  await step2_getseq(arg);
}
async function step2_getseq(arg) {
  if (arg.model.genomicseq) {
    checker();
    step2_getpdomain(arg);
    return;
  }
  const par = {
    genome: arg.genome.name,
    coord: arg.model.chr + ":" + (arg.model.start + 1) + "-" + arg.model.stop
  };
  const data = await dofetch3("ntseq", { method: "POST", body: JSON.stringify(par) });
  if (!data) throw "getting sequence: server error";
  if (data.error) throw "getting sequence: " + data.error;
  if (!data.seq) throw "no nt seq???";
  arg.model.genomicseq = data.seq.toUpperCase();
  arg.model.aaseq = nt2aa(arg.model);
  checker();
  await step2_getpdomain(arg);
  function checker() {
    if (arg.model.aaseq) {
      const stop = arg.model.aaseq.indexOf(codon_stop);
      const cdslen = arg.model.cdslen - (arg.model.startCodonFrame ? 3 - arg.model.startCodonFrame : 0);
      if (stop != -1 && stop < cdslen / 3 - 1) {
        sayerror(arg.holder, "Translating " + arg.model.isoform + " ends at " + stop + " AA, expecting " + cdslen / 3);
      }
    }
  }
}
async function step2_getpdomain(arg) {
  const isoform2gm = /* @__PURE__ */ new Map();
  for (const m of arg.allmodels) {
    if (!m.pdomains) {
      m.pdomains = [];
      m.domain_hidden = {};
      if (!isoform2gm.has(m.isoform)) isoform2gm.set(m.isoform, []);
      isoform2gm.get(m.isoform).push(m);
    }
  }
  if (isoform2gm.size == 0) {
    await step3(arg);
    return;
  }
  const data = await dofetch3("pdomain", {
    method: "POST",
    body: JSON.stringify({ genome: arg.genome.name, isoforms: [...isoform2gm.keys()] })
  });
  if (data.error) throw "error getting protein domain: " + data.error;
  if (!Array.isArray(data.lst)) throw ".lst[] not array";
  for (const a of data.lst) {
    for (const m of isoform2gm.get(a.name)) {
      m.pdomains = a.pdomains;
    }
  }
  if (arg.geneDomains) {
    if (typeof arg.geneDomains != "object") throw "geneDomains not object";
    for (const isoform in arg.geneDomains) {
      const lst = isoform2gm.get(isoform);
      if (!lst) throw `unknown isoform ${isoform} from geneDomains{}`;
      for (const g of lst) {
        if (!g.pdomains) g.pdomains = [];
        if (!Array.isArray(arg.geneDomains[isoform])) throw `geneDomains[${isoform}] not array`;
        for (const b of arg.geneDomains[isoform]) {
          if (typeof b != "object") throw "element from geneDomains[] not object";
          if (!Number.isInteger(b.start)) throw "start not integer from geneDomains[]";
          if (!Number.isInteger(b.stop)) throw "stop not integer from geneDomains[]";
          if (b.start > b.stop) throw "start>stop from geneDomains[]";
          if (!b.name) b.name = "Custom domain";
          if (!g.pdomains.find((a) => a.start == b.start && a.stop == b.stop && a.name == b.name)) g.pdomains.push(b);
        }
      }
    }
  }
  const s = proteinDomainColorScale();
  for (const lst of isoform2gm.values()) {
    for (const g of lst) {
      for (const d of g.pdomains || []) {
        if (!d.color) d.color = s(d.name + d.description);
      }
    }
  }
  await step3(arg);
}
async function step3(arg) {
  let mode = arg.gmmode;
  if (!mode) {
    if (arg.model.cdslen) {
      mode = gmmode.protein;
    } else {
      mode = gmmode.exononly;
    }
  }
  if (arg.dataset) {
    if (!Array.isArray(arg.dataset)) throw "dataset is not array";
    for (const dsname of arg.dataset) {
      if (arg.genome.datasets[dsname] && !arg.genome.datasets[dsname].legacyDsIsUninitiated) continue;
      const d = await dofetch3(`getDataset?genome=${arg.genome.name}&dsname=${dsname}`);
      if (d.error) throw `invalid name from dataset[]: ${d.error}`;
      if (!d.ds) throw ".ds missing";
      const ds = arg.genome.datasets[d.ds.label];
      Object.assign(ds, d.ds);
      const _ = await import("./legacyDataset-SWJCAWIR.js");
      _.validate_oldds(ds);
      delete ds.legacyDsIsUninitiated;
    }
  }
  const b = await import("./block-TTN2IQAH.js");
  arg.__blockInstance = new b.Block({
    genome: arg.genome,
    holder: arg.holder,
    nobox: true,
    usegm: arg.model,
    gmstackheight: 37,
    allgm: arg.allmodels,
    datasetlst: arg.dataset,
    legacyDsFilter: arg.legacyDsFilter,
    mset: arg.mset,
    hlaachange: arg.hlaachange,
    hlvariants: arg.hlvariants,
    hlregions: arg.hlregions,
    gmmode: mode,
    hidedatasetexpression: arg.hidedatasetexpression,
    hidegenecontrol: arg.hidegenecontrol,
    hidegenelegend: arg.hidegenelegend,
    variantPageCall_snv: arg.variantPageCall_snv,
    datasetqueries: arg.datasetqueries,
    samplecart: arg.samplecart,
    debugmode: arg.debugmode,
    tklst: arg.tklst,
    mclassOverride: arg.mclassOverride,
    hide_dsHandles: arg.hide_dsHandles,
    onloadalltk_always: arg.onloadalltk_always,
    onAddRemoveTk: arg.onAddRemoveTk
  });
}

export {
  string2snp,
  block_init_default
};
//# sourceMappingURL=chunk-67DBIM6H.js.map
