import { hashQueryKeyByOptions as n, matchQuery as o } from "./utils.js";
import { Query as l } from "./query.js";
import { notifyManager as i } from "./notifyManager.js";
import { Subscribable as u } from "./subscribable.js";
var g = class extends u {
  constructor(t = {}) {
    super(), this.config = t, this.#t = /* @__PURE__ */ new Map();
  }
  #t;
  build(t, e, s) {
    const h = e.queryKey, a = e.queryHash ?? n(h, e);
    let r = this.get(a);
    return r || (r = new l({
      client: t,
      queryKey: h,
      queryHash: a,
      options: t.defaultQueryOptions(e),
      state: s,
      defaultOptions: t.getQueryDefaults(h)
    }), this.add(r)), r;
  }
  add(t) {
    this.#t.has(t.queryHash) || (this.#t.set(t.queryHash, t), this.notify({
      type: "added",
      query: t
    }));
  }
  remove(t) {
    const e = this.#t.get(t.queryHash);
    e && (t.destroy(), e === t && this.#t.delete(t.queryHash), this.notify({ type: "removed", query: t }));
  }
  clear() {
    i.batch(() => {
      this.getAll().forEach((t) => {
        this.remove(t);
      });
    });
  }
  get(t) {
    return this.#t.get(t);
  }
  getAll() {
    return [...this.#t.values()];
  }
  find(t) {
    const e = { exact: !0, ...t };
    return this.getAll().find(
      (s) => o(e, s)
    );
  }
  findAll(t = {}) {
    const e = this.getAll();
    return Object.keys(t).length > 0 ? e.filter((s) => o(t, s)) : e;
  }
  notify(t) {
    i.batch(() => {
      this.listeners.forEach((e) => {
        e(t);
      });
    });
  }
  onFocus() {
    i.batch(() => {
      this.getAll().forEach((t) => {
        t.onFocus();
      });
    });
  }
  onOnline() {
    i.batch(() => {
      this.getAll().forEach((t) => {
        t.onOnline();
      });
    });
  }
};
export {
  g as QueryCache
};
