import { ref, watch } from 'vue';
export function timeout(delay: number = 0) {
  return new Promise<void>((resolve) => setTimeout(resolve, delay));
}
export class IdDispenser {
  #maxId: number;
  #usedIdSet: Set<number>;
  #unUsedIdSet: Set<number>;
  constructor() {
    this.#maxId = 0;
    this.#usedIdSet = new Set<number>();
    this.#unUsedIdSet = new Set<number>();
  }
  getId(...identifiersToRemove: number[]) {
    let id: number;
    if (this.#unUsedIdSet.size) {
      [id] = this.#unUsedIdSet;
      this.#unUsedIdSet.delete(id);
    } else {
      id = this.#maxId++;
    }
    this.#usedIdSet.add(id);
    this.removeId(...identifiersToRemove);
    return id;
  }
  removeId(...identifiers: number[]) {
    for (const id of identifiers) {
      if (!this.#usedIdSet.delete(id)) {
        return;
      }
      this.#unUsedIdSet.add(id);
    }
  }
  reset() {
    this.#maxId = 0;
    this.#unUsedIdSet.clear();
    this.#usedIdSet.clear();
  }
}

export function useRefresh() {
  const dispenser = new IdDispenser();
  const key = ref(dispenser.getId());
  watch(key, (value) => console.log(value));
  return {
    key,
    refresh() {
      key.value = dispenser.getId(key.value);
    }
  };
}

export * from './2d-array';
export * from './api';
