import { _decorator, assetManager, Component, director, find, Material, MeshRenderer, Node, resources, SkeletalAnimation } from 'cc';
import { FruitPoolManager } from './FruitPoolManager';
const { ccclass, property } = _decorator;

@ccclass('test2')
export class test2 extends Component {

    @property(Node)
    m: Node = null;

    private prefabs = ["fruit/prefab/apple","fruit/prefab/banana",
                        "fruit/prefab/durian","fruit/prefab/hamimelon",
                        "fruit/prefab/pineapple","fruit/prefab/orange",
                        "fruit/prefab/strawberry","fruit/prefab/watermelon"]

    start() {
        this.scheduleOnce(() => {
            director.purgeDirector()
            if(this.m){
                // this.destroy_MeshRenderer(this.m) //回不回收结果都一样
            }
            this.showGPU()
            this.loadScene("scene")
        },3)

        this.prefabs.forEach(item=>{
            if(!FruitPoolManager.instance.isPool(item)){
                FruitPoolManager.instance.loadPrefab(item)
            }
        })
       
    }


    protected onEnable(): void {
        // super.onEnable();

        this.scheduleOnce(()=>{
            this.prefabs.forEach(item=>{
                let ndFruit = FruitPoolManager.instance.getNodePool(item, this.m) as Node;
                ndFruit.active = true
                ndFruit.setPosition(0, 0)
            })
        },2)

    }


    
    
    loadScene(_scene){
        director.loadScene(_scene, () => {
                
            }
        );

    }

    showGPU(){

        const device = director.root?.device;
            const bufferSizeMB = device?.memoryStatus.bufferSize / (1024 * 1024);
            console.log('bufferSize = ',device?.memoryStatus.bufferSize, JSON.stringify({
                // textures: device?.memoryStatus.textureSize,    // 纹理内存
                buffers: bufferSizeMB+"MB",     // 顶点/索引缓冲
                // drawCalls: device?.numDrawCalls,
                // numTris: device?.numTris,
                // bufferMemory:gpuInfo.bufferMemory.counter.value ,
                // textureMemory:gpuInfo.textureMemory.counter.value

                // framebuffers: device.memoryStatus.fboSize,   // 帧缓冲对象
                // programs: device.memoryStatus.programSize    // 着色器程序
            }))

    }

    clear_SkeletalAnimation(sa: SkeletalAnimation) {
        sa.stop()
        sa.destroy()
    }



    destroy_MeshRenderer( node: Node ) {
        const meshes = node.getComponentsInChildren(MeshRenderer);
        meshes.forEach(mr => this.clear_MeshRenderer(mr));
    }

    clear_MeshRenderer(mesh: MeshRenderer) {
    // 0. 安全检查
        if (!mesh || !mesh.isValid || !mesh.node?.isValid) return;

        // 1. 禁用并解除节点关系
        mesh.enabled = false;
        mesh.node.active = false;
        mesh.node.removeFromParent();
        // mesh.node.removeComponent(MeshRenderer);

        // 2. 清理 Mesh 资源
        if (mesh.mesh?.isValid) {
            // 先解除引用再释放
            const meshAsset = mesh.mesh;
            assetManager.releaseAsset(meshAsset);
            meshAsset.destroyRenderingMesh(); 
            // if (mesh.mesh && mesh.mesh.isValid) {
            //     mesh.mesh.destroy(); // 安全销毁
            // }
            mesh.mesh = null; // 必须先置空！
            // 安全释放 GPU 资源
        }

        // 3. 清理 Material 资源（重要！）
        // if (mesh?.materials && mesh.materials.length > 0) {
            // const mat = mesh.materials;
            // for (const k in mesh.materials) {
                // const mat = mesh.materials[k];
                // if (!mat.refCount || mat.refCount <= 1) {
                    // mat.destroy();
                // }
            // }
            // 如果是共享材质，不要直接 destroy！
            // mesh.material = null;
        // }

        // 4. 销毁节点（会自动销毁所有组件）
        mesh.node.destroy(); // 不要单独调用 mesh.destroy()！
        // if (mesh && mesh.isValid) {
        //     mesh.destroy(); // 安全销毁
        // }
    }

      

    
}


