import { startCancelableOperation as o, Deferred as u, isOperationCancelled as a } from "../utils/promise-utils.js";
import { c as n } from "../../../../../../../_virtual/cancellation.js";
class p {
  constructor() {
    this.previousTokenSource = new n.CancellationTokenSource(), this.writeQueue = [], this.readQueue = [], this.done = !0;
  }
  write(e) {
    this.cancelWrite();
    const t = o();
    return this.previousTokenSource = t, this.enqueue(this.writeQueue, e, t.token);
  }
  read(e) {
    return this.enqueue(this.readQueue, e);
  }
  enqueue(e, t, s = n.CancellationToken.None) {
    const i = new u(), r = {
      action: t,
      deferred: i,
      cancellationToken: s
    };
    return e.push(r), this.performNextOperation(), i.promise;
  }
  async performNextOperation() {
    if (!this.done)
      return;
    const e = [];
    if (this.writeQueue.length > 0)
      e.push(this.writeQueue.shift());
    else if (this.readQueue.length > 0)
      e.push(...this.readQueue.splice(0, this.readQueue.length));
    else
      return;
    this.done = !1, await Promise.all(e.map(async ({ action: t, deferred: s, cancellationToken: i }) => {
      try {
        const r = await Promise.resolve().then(() => t(i));
        s.resolve(r);
      } catch (r) {
        a(r) ? s.resolve(void 0) : s.reject(r);
      }
    })), this.done = !0, this.performNextOperation();
  }
  cancelWrite() {
    this.previousTokenSource.cancel();
  }
}
export {
  p as DefaultWorkspaceLock
};
