// @ts-nocheck
export class PDFPageViewBuffer {
  private _buf = new Set()

  private _size: number = 0

  constructor(size: number) {
    this._size = size;
  }

  push(view: any) {
    const buf = this._buf;
    if (buf.has(view)) {
      buf.delete(view); // Move the view to the "end" of the buffer.
    }
    buf.add(view);

    if (buf.size > this._size) {
      this._destroyFirstView();
    }
  }

  resize(newSize, idsToKeep = null) {
    this._size = newSize;

    const buf = this._buf;
    if (idsToKeep) {
      const ii = buf.size;
      let i = 1;
      for (const view of buf) {
        if (idsToKeep.has(view.id)) {
          buf.delete(view); // Move the view to the "end" of the buffer.
          buf.add(view);
        }
        if (++i > ii) {
          break;
        }
      }
    }

    while (buf.size > this._size) {
      this._destroyFirstView();
    }
  }

  has(view) {
    return this._buf.has(view);
  }

  [Symbol.iterator]() {
    return this._buf.keys();
  }

  private _destroyFirstView() {
    const firstView = this._buf.keys().next().value;

    firstView?.destroy();
    this._buf.delete(firstView);
  }
}
