using Cysharp.Threading.Tasks;
using YooAsset;

public class MainOperation 
{
    PatchOperationData data;
    PatchOperation operation;
    bool autoDownload;
    public MainOperation(EPlayMode playMode, bool autoDownload = false)
    {
        data = new PatchOperationData();
        data.packageName = "Main";
        data.playMode = playMode;
        data.useBuildinFileSystem = false;
        data.downloadingMaxNum = 10;
        data.failedTryAgain = 3;
        data.downloadUpdate = OnDownloadUpdate;
        data.downloadFinish = OnDownloadFinish;
        data.downloadError = OnDownloadError;

        operation = new PatchOperation(data);
        this.autoDownload = autoDownload;
    }

    public async UniTask Execute()
    {
        PatchEvent.UpdateProgress(0f);
        if (!await operation.InitializePackage()) return;
        if (!await operation.RequestPackageVersion()) return;
        if (!await operation.UpdatePackageManifest()) return;
        if (operation.CreateDownloader()) 
        {
            if (autoDownload)
            {
                if (!await operation.DownloadPackageFiles()) return;
            }
            else
            {
                if (!await operation.CheckDownloadOrSkip()) return;
            }
        }
        if (!await operation.ClearCacheBundle()) return;
        operation.SaveVersionToCache();
        YooAssets.SetDefaultPackage(operation.package);
    }
    private void OnDownloadUpdate(DownloadUpdateData  downloadUpdateData)
    {
        float progress = (float)downloadUpdateData.CurrentDownloadBytes / downloadUpdateData.TotalDownloadBytes;
        string sizeText = $"{operation.FormatFileSize(downloadUpdateData.CurrentDownloadBytes)} / {operation.FormatFileSize(downloadUpdateData.TotalDownloadBytes)}";
        PatchEvent.UpdateProgress(progress);
        PatchEvent.UpdateDownloadSize(sizeText);
        PatchEvent.UpdateStatus($"{data.packageName} 资源下载中...");
    }
    private void OnDownloadFinish(DownloaderFinishData  downloaderFinishData)
    {
        PatchEvent.UpdateStatus("下载完成");
    }
    private void OnDownloadError(DownloadErrorData downloadErrorData)
    {
        PatchEvent.UpdateStatus($"下载失败:{downloadErrorData.FileName}\n{downloadErrorData.ErrorInfo}");
    }
}
