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

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) {
        MTweenMgr.instance.removeTweens(element);
        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;
}