import { MUtils } from "../Global/MUtils";

export default abstract class Pool<T extends PoolElement>{
    private data: T[] = [];

    public get(...args: any[]): T {
        if (this.data.length > 0) {
            let e = this.data.pop();
            e.onElementInit();
            return e;
        } else {
            return this.createElement(...args);
        }
    }

    public recycle(element: T) {
        element.onElementRecycle();
        for (let i of this.data) {
            if (i === element) return;
        }
        this.data.push(element);
    }

    protected abstract createElement(...args: any[]): T;
}

export abstract class PoolGroup<T extends PoolElement>{
    private data: {
        [key: string]: Pool<T>
    } = {};

    public get(key: string): T {
        return this.getValue(key).get();
    }

    public recycle(key: string, element: T) {
        this.getValue(key).recycle(element);
    }

    private getValue(key: string) {
        this.data[key] = this.data[key] || this.createPool(key);
        return this.data[key];
    }

    protected abstract createPool(key: string): Pool<T>;
}

export interface PoolElement {
    onElementRecycle(): void;
    onElementInit(): void;
}