// retoor <retoor@molodetz.nl>

const BASE_Z = 2147480000;
const CEILING_Z = 2147483400;

export default class WindowManager {
  constructor() {
    this._z = BASE_Z;
    this._windows = new Set();
  }

  register(win) {
    this._windows.add(win);
    this.focus(win);
  }

  unregister(win) {
    this._windows.delete(win);
  }

  focus(win) {
    if (!win) return;
    if (this._z >= CEILING_Z) this._renormalize();
    this._z += 1;
    try {
      win.style.zIndex = String(this._z);
    } catch (error) {
      return;
    }
  }

  _renormalize() {
    const ordered = Array.from(this._windows).sort(
      (a, b) => (parseInt(a.style.zIndex, 10) || 0) - (parseInt(b.style.zIndex, 10) || 0),
    );
    this._z = BASE_Z;
    ordered.forEach((win) => {
      this._z += 1;
      try {
        win.style.zIndex = String(this._z);
      } catch (error) {
        return;
      }
    });
  }
}
