using Cysharp.Threading.Tasks;
using System.Threading.Tasks;
using UnityEngine;
using YooAsset;

public class PreloadOperation 
{
    PatchOperationData data;
    PatchOperation operation;
    public PreloadOperation(EPlayMode playMode)
    {
        data = new PatchOperationData();
        data.packageName = "Preload";
        data.playMode = playMode;
        data.useBuildinFileSystem = true;
        data.downloadingMaxNum = 10;
        data.failedTryAgain = 3;

        operation = new PatchOperation(data);
    }
    public async UniTask Execute() 
    {
#if !UNITY_EDITOR
        CheckIsOffline();
#endif
        if (!await operation.InitializePackage()) return;
        var version = await GetBestPackageVersion();
#if UNITY_EDITOR
        if (!await operation.RequestPackageVersion()) return;
        version = operation.packageVersion;
#endif
        //获取版本失败
        if (version == null)
        {
            MessageBox.Show()
                      .SetTitle($"{operation.data.packageName}获取版本")
                      .SetContent("获取版本失败")
                      .AddButton("退出", (box) => { Application.Quit(); });
            return;
        }
        operation.packageVersion = version;
        if (!await operation.UpdatePackageManifest()) return;
        await HotDllLoader.Inst.LoadDll(YooAssets.GetPackage("Preload"), "GameScripts.Preload");
        await LoadAndShowPatchWindow();
        MainUICanvas.Inst.InitBg.SetActive(false);
        _ = UpdatePreloadPackage();
    }
    void CheckIsOffline()
    {
        if (string.IsNullOrEmpty(operation.GetCachedPackageVersion()))
        {
            operation.data.playMode = EPlayMode.OfflinePlayMode;
        }
    }
    async Task<string> GetBestPackageVersion()
    {
        string cachedVersion = operation.GetCachedPackageVersion();
        if (!string.IsNullOrEmpty(cachedVersion))
        {
            return cachedVersion;
        }
        string buildinVersion = await operation.GetBuildinPackageVersion();
        if (!string.IsNullOrEmpty(buildinVersion))
        {
            return buildinVersion;
        }
        return null;
    }
    private async UniTask LoadAndShowPatchWindow()
    {
        var assetHandle = operation.package.LoadAssetAsync<GameObject>("PatchWindow");
        await assetHandle.ToUniTask();
        if (assetHandle.Status == EOperationStatus.Succeed)
            GameObject.Instantiate(assetHandle.AssetObject, MainUICanvas.Inst.Medium);
        Debug.Log("创建热更信息界面");
    }
    private async UniTask UpdatePreloadPackage()
    {
        if (!await operation.RequestPackageVersion(false)) return;
        if (!await operation.UpdatePackageManifest(false)) return;
        if (operation.CreateDownloader())
        {
            if (!await operation.DownloadPackageFiles()) return;
        }
        if (!await operation.ClearCacheBundle()) return;
        operation.SaveVersionToCache();
    }
}
