using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
using Tuan.GameFramework;

namespace Tuan.GameScripts.Main
{
    public class AssetLoader :Singleton <AssetLoader>
    {
        Dictionary<string, AssetHandle> assetHandles = new Dictionary<string, AssetHandle>();
        public async UniTask<T> LoadAsync<T>(string name, LoadingWindow loadingWindow = null) where T : UnityEngine.Object
        {
            AssetHandle handle = null;
            if (!assetHandles.ContainsKey(name))
            {
                handle = YooAssets.LoadAssetAsync<T>(name);
                await handle.ToUniTask(loadingWindow);
                assetHandles.Add(name, handle);
                Debug.Log($"AssetLoad:{name}");
            }
            else
            {
                handle = assetHandles[name];
                Debug.Log($"AssetLoad:{name}(已缓存handle)");
            }
            if (loadingWindow != null)
                UIManager.Inst.CloseUI(loadingWindow);
            return handle.AssetObject as T;
        }
        public T Load<T>(string name) where T : UnityEngine.Object
        {
            AssetHandle handle = null;
            if (!assetHandles.ContainsKey(name))
            {
                handle = YooAssets.LoadAssetSync<T>(name);
                assetHandles.Add(name, handle);
                Debug.Log($"AssetLoad:{name}");
            }
            else
            {
                handle = assetHandles[name];
                Debug.Log($"AssetLoad:{name}(已缓存handle)");
            }
            return handle.AssetObject as T;
        }
        public AssetHandle GetHandle(string name)
        {
            if (assetHandles.ContainsKey(name))
                return assetHandles[name];
            return null;
        }
    }
}