// objectPool.ts
import type { ObjectPool, PooledObject } from "./types"

export class Pool<T extends PooledObject> implements ObjectPool<T> {
  public objects: T[] = []
  public maxSize: number = 0
  public createFn: () => T
  public resetFn: (obj: T) => void

  constructor(maxSize: number, createFn: () => T, resetFn: (obj: T) => void) {
    this.maxSize = maxSize
    this.createFn = createFn
    this.resetFn = resetFn

    // Pre-allocate objects
    for (let i = 0; i < maxSize; i++) {
      const obj = createFn()
      obj.active = false
      this.objects.push(obj)
    }
  }

  get(): T | null {
    for (let i = 0; i < this.objects.length; i++) {
      if (!this.objects[i].active) {
        this.objects[i].active = true
        return this.objects[i]
      }
    }
    return null // Pool exhausted
  }

  release(obj: T): void {
    obj.active = false
    this.resetFn(obj)
  }

  releaseAll(): void {
    for (let i = 0; i < this.objects.length; i++) {
      if (this.objects[i].active) {
        this.release(this.objects[i])
      }
    }
  }

  getActiveObjects(): T[] {
    return this.objects.filter((obj) => obj.active)
  }

  getActiveCount(): number {
    return this.objects.filter((obj) => obj.active).length
  }
}
