import { INTERNAL_EVT_SESSION_DEADLINE as h } from "./constants.js";
import { createAbortable as S } from "../../../async/abortable/main.js";
import { createEventEmitter as v } from "../../../reactive/eventEmitter/main.js";
import { createPromisor as y } from "../../../async/promisor/main.js";
import { isAbortSignal as A, abortSignalForAny as D, abortedSignal as k } from "../../../../utils/abort/main.js";
import { clock as I } from "../../../time/clock/main.js";
import { isWatchlistUnsubscribeToken as N } from "../../../reactive/watchlist/main.js";
import { struct as w } from "../../../../utils/struct/main.js";
import { getter as u, enumerable as c } from "../../../../utils/struct/property.js";
import { tryResolve as F } from "../../../../utils/async/main.js";
import { noop as L } from "../../../../utils/common.js";
import { parseDate as T } from "../../../../utils/datetime/main.js";
import { isFunction as C } from "../../../../utils/value/is.js";
const K = (P, b) => {
  let r, t = 1 / 0, p, l;
  const i = S(), _ = v(), m = () => {
    r?.removeEventListener("abort", m), t = 1 / 0, l?.(), i.refresh(), _.emit(h);
  }, E = y(async (o, n) => {
    p = o;
    const d = await F(() => {
      const e = b.deadline;
      return C(e) ? e.call(b, n, o) : e;
    }).catch(L);
    if (p !== o) return;
    const f = (Array.isArray(d) ? d : [d]).filter((e) => e || e === 0);
    if (f.length > 0) {
      let e = !1;
      const a = /* @__PURE__ */ new Set();
      for (const s of f)
        if (A(s)) {
          if (e = s.aborted) break;
          a.add(s);
        } else if (t = Math.min(t, T(s) ?? 1 / 0), e = t <= Date.now()) break;
      e ||= a.size < 1 && !Number.isFinite(t), e ? r ??= k() : (r = D([...a, i.signal]), r.addEventListener("abort", m), g()), f.length = 0, a.clear();
    } else
      r = void 0, i.refresh();
  }), g = () => {
    if (!Number.isFinite(t)) return;
    let o = I.subscribe((n) => {
      if (N(n)) return m();
      n.now >= t && i.abort();
    });
    l = () => {
      o?.(), o = l = void 0;
    };
  };
  return w({
    elapse: c(i.abort),
    elapsed: u(() => r && r.aborted),
    on: c(_.on),
    refresh: c(E.bind(void 0)),
    signal: u(() => i.signal)
  });
};
export {
  K as createSessionDeadline
};
