import { _decorator, Asset } from 'cc';
const { ccclass } = _decorator;

@ccclass('ResourceManager')
export class ResourceManager {
    private static _instance: ResourceManager;
    private cache: Map<string, Asset> = new Map();

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

    /** 存资源 */
    set(key: string, asset: Asset) {
        this.cache.set(key, asset);
    }

    /** 取资源 */
    get<T extends Asset>(key: string): T | undefined {
        return this.cache.get(key) as T | undefined;
    }

    /** 是否存在 */
    has(key: string): boolean {
        return this.cache.has(key);
    }

    /** 释放某个资源 */
    release(key: string) {
        const asset = this.cache.get(key);
        if (asset) {
            asset.decRef(); // 减少引用计数
            this.cache.delete(key);
        }
    }

    /** 释放全部资源 */
    releaseAll() {
        this.cache.forEach(asset => asset.decRef());
        this.cache.clear();
    }
}
