import { _decorator, Node, instantiate, Pool } from 'cc';
import Singleton from '../plugin/Singleton';

export default class TilePoolMgr extends Singleton {
    private static _tilePool: Pool<Node> = null;
    private static _tileCell: Node = null;
    private static _allNodes: Set<Node> = new Set();
    /**
   * 初始化节点池
   * @param tileTemplate 地块节点模板
   * @param preloadCount 预加载数量
   */
    public static init(tileTemplate: Node, preloadCount: number = 10): void {
        if (this._tilePool) {
            console.warn('TilePoolManager already initialized!');
            return;
        }

        this._tileCell = tileTemplate;
        this._tilePool = new Pool(
            () => {
                const newNode = instantiate(this._tileCell);
                this._allNodes.add(newNode);
                return newNode;
            },
            81,
            (node: Node) => {
                node.removeFromParent();
                node.active = false;
            }
        );

        // 预加载节点
        this.preload(preloadCount);

    }
    /**
     * 预加载节点
     * @param count 预加载数量
     */
    private static preload(count: number): void {
        const nodes: Node[] = [];
        for (let i = 0; i < count; i++) {
            nodes.push(this._tilePool.alloc());
        }
        nodes.forEach(node => this._tilePool.free(node));
    }

    /**
     * 从池中获取一个节点
     */
    public static get(): Node {
        if (!this._tilePool) {
            console.error('TilePoolManager not initialized!');
            return null;
        }
        let node = this._tilePool.alloc();
        node.active = true;
        return node;
    }

    /**
     * 回收节点到池中
     * @param node 要回收的节点
     */
    public static put(node: Node): void {
        if (!this._tilePool) {
            console.error('TilePoolManager not initialized!');
            return;
        }
        if (!node) {
            console.warn('Trying to put null node into pool');
            return;
        }
        this._tilePool.free(node);
    }
}