import { _decorator, Asset, Node, Prefab, instantiate, AssetManager, assetManager, sys } from 'cc';

export class ResManager {
    private static _instance: ResManager = null;

    public static get instance(): ResManager {
        if (!this._instance) {
            this._instance = new ResManager();
        }
        return this._instance;
    }

    async loadPrefabFromBundle(bundleName: string, path: string, progressCallback?: (finished: number, total: number) => void): Promise<Node> {
        try {
            if (!sys.isBrowser) {
                assetManager.cacheManager.cacheEnabled = true;
            }

            let bundle = await new Promise<AssetManager.Bundle>((resolve, reject) => {
                // let existingBundle = assetManager.getBundle(bundleName);
                // if (existingBundle) {
                //     progressCallback?.(1, 1);
                //     resolve(existingBundle);
                //     return;
                // }

                assetManager.loadBundle(bundleName,
                    (finished, total) => progressCallback?.(finished, total),
                    (err, bundle) => err ? reject(err) : resolve(bundle)
                );
            });
            
            let prefab = await new Promise<Prefab>((resolve, reject) => {
                bundle.load(path, Prefab, (err, prefab) => {
                    if (err) reject(err);
                    else resolve(prefab);
                });
            });


            // let prefabData = JSON.stringify(prefab);
            // let newPrefab = JSON.parse(prefabData);
            // 3. 实例化
            return instantiate(prefab);

        } catch (error) {
            console.error(`加载失败: ${bundleName}/${path}`, error);
            throw error;
        }
    }
}