using System;
using Fantasy.Async;
using NBC;
using UnityEngine.SceneManagement;

namespace NBF
{
    public static class SceneHelper
    {
        public static async FTask LoadScene(string sceneName)
        {
            try
            {
                Game.Main.EventComponent.Publish(new SceneChangeStart());
                LoadingPanel.Show();
                var asyncOperation = SceneManager.LoadSceneAsync(sceneName);
                if (asyncOperation == null) throw new Exception($"Scene not found,name={sceneName}");
                while (true)
                {
                    await Game.Main.EventComponent.PublishAsync(new LoadingProgress()
                    {
                        Progress = asyncOperation.progress
                    });
                    LoadingPanel.SetProgress(asyncOperation.progress);
                    // 等待0.5秒后执行下面的逻辑。
                    await Game.Main.TimerComponent.Net.WaitAsync(500);
                    if (asyncOperation.isDone)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
    }
}