using Cysharp.Threading.Tasks;
using HybridCLR;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using YooAsset;

public class HotDllLoader : Singleton<HotDllLoader>
{
    public List<string> DepDlls = new List<string>()
    {
        "mscorlib.dll",
        "System.dll",
        "System.Core.dll",
    };
    public async UniTask LoadDll(ResourcePackage package, string dll)
    {
        if (package.GetAssetInfo(dll).Error == string.Empty)
        {
            AssetHandle handle = package.LoadAssetAsync<TextAsset>(dll);
            await handle.ToUniTask();
#if UNITY_EDITOR
            Assembly hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == dll.Replace(".dll", ""));
#else
            Assembly hotUpdateAss = Assembly.Load((handle.AssetObject as TextAsset).bytes);
#endif
            Debug.Log($"加载{dll}");
        }
    }
    public async UniTask LoadDepDll(ResourcePackage package)
    {
        foreach (string dll in DepDlls)
        {
            if (package.GetAssetInfo(dll).Error == string.Empty)
            {
                AssetHandle handle = package.LoadAssetAsync<TextAsset>(dll);
                await handle.ToUniTask();
                RuntimeApi.LoadMetadataForAOTAssembly((handle.AssetObject as TextAsset).bytes, HomologousImageMode.SuperSet);
            }
        }
    }
}
