import { ArraySet } from "./ArraySet.mjs";
import { HistoryBuffer } from "./HistoryBuffer.mjs";
import { maybeCaptureParent, startCapturingParents, stopCapturingParents } from "./capture.mjs";
import { GLOBAL_START_EPOCH } from "./constants.mjs";
import { EMPTY_ARRAY, equals, haveParentsChanged } from "./helpers.mjs";
import { globalEpoch } from "./transactions.mjs";
import { RESET_VALUE } from "./types.mjs";
const UNINITIALIZED = Symbol("UNINITIALIZED");
const isUninitialized = (value) => {
  return value === UNINITIALIZED;
};
class WithDiff {
  constructor(value, diff) {
    this.value = value;
    this.diff = diff;
  }
}
function withDiff(value, diff) {
  return new WithDiff(value, diff);
}
class _Computed {
  constructor(name, derive, options) {
    this.name = name;
    this.derive = derive;
    if (options?.historyLength) {
      this.historyBuffer = new HistoryBuffer(options.historyLength);
    }
    this.computeDiff = options?.computeDiff;
    this.isEqual = options?.isEqual ?? equals;
  }
  lastChangedEpoch = GLOBAL_START_EPOCH;
  lastTraversedEpoch = GLOBAL_START_EPOCH;
  /**
   * The epoch when the reactor was last checked.
   */
  lastCheckedEpoch = GLOBAL_START_EPOCH;
  parents = [];
  parentEpochs = [];
  children = new ArraySet();
  get isActivelyListening() {
    return !this.children.isEmpty;
  }
  historyBuffer;
  // The last-computed value of this signal.
  state = UNINITIALIZED;
  computeDiff;
  isEqual;
  __unsafe__getWithoutCapture() {
    const isNew = this.lastChangedEpoch === GLOBAL_START_EPOCH;
    if (!isNew && (this.lastCheckedEpoch === globalEpoch || !haveParentsChanged(this))) {
      this.lastCheckedEpoch = globalEpoch;
      return this.state;
    }
    try {
      startCapturingParents(this);
      const result = this.derive(this.state, this.lastCheckedEpoch);
      const newState = result instanceof WithDiff ? result.value : result;
      if (this.state === UNINITIALIZED || !this.isEqual(newState, this.state)) {
        if (this.historyBuffer && !isNew) {
          const diff = result instanceof WithDiff ? result.diff : void 0;
          this.historyBuffer.pushEntry(
            this.lastChangedEpoch,
            globalEpoch,
            diff ?? this.computeDiff?.(this.state, newState, this.lastCheckedEpoch, globalEpoch) ?? RESET_VALUE
          );
        }
        this.lastChangedEpoch = globalEpoch;
        this.state = newState;
      }
      this.lastCheckedEpoch = globalEpoch;
      return this.state;
    } finally {
      stopCapturingParents();
    }
  }
  get value() {
    const value = this.__unsafe__getWithoutCapture();
    maybeCaptureParent(this);
    return value;
  }
  getDiffSince(epoch) {
    this.value;
    if (epoch >= this.lastChangedEpoch) {
      return EMPTY_ARRAY;
    }
    return this.historyBuffer?.getChangesSince(epoch) ?? RESET_VALUE;
  }
}
function computedAnnotation(options = {}, _target, key, descriptor) {
  const originalMethod = descriptor.get;
  const derivationKey = Symbol.for("__@tldraw/state__computed__" + key);
  descriptor.get = function() {
    let d = this[derivationKey];
    if (!d) {
      d = new _Computed(key, originalMethod.bind(this), options);
      Object.defineProperty(this, derivationKey, {
        enumerable: false,
        configurable: false,
        writable: false,
        value: d
      });
    }
    return d.value;
  };
  return descriptor;
}
function getComputedInstance(obj, propertyName) {
  const key = Symbol.for("__@tldraw/state__computed__" + propertyName.toString());
  let inst = obj[key];
  if (!inst) {
    obj[propertyName];
    inst = obj[key];
  }
  return inst;
}
function computed() {
  if (arguments.length === 1) {
    const options = arguments[0];
    return (target, key, descriptor) => computedAnnotation(options, target, key, descriptor);
  } else if (typeof arguments[0] === "string") {
    return new _Computed(arguments[0], arguments[1], arguments[2]);
  } else {
    return computedAnnotation(void 0, arguments[0], arguments[1], arguments[2]);
  }
}
function isComputed(value) {
  return value && value instanceof _Computed;
}
export {
  _Computed,
  computed,
  getComputedInstance,
  isComputed,
  isUninitialized,
  withDiff
};
//# sourceMappingURL=Computed.mjs.map
