using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace ChillConnect
{
    public sealed class SceneSwitchManager : BaseUnityManager<SceneSwitchManager>
    {
        private const bool IsUseUnityScene = false;

        public delegate void LoadCallBack(object param);

        public void SwitchInitialScene(int idx, LoadCallBack loadHandler, object param)
        {
            StartCoroutine(OnLoadInitialScene(idx, loadHandler, param));
        }

        public void SwitchScene(int idx, LoadCallBack loadHandler, object param)
        {
            StartCoroutine(OnLoadScene(idx, loadHandler, param));
        }

        private IEnumerator OnLoadInitialScene(int idx, LoadCallBack loadHandle, object param)
        {
            yield return YieldConst.Time10ms;

            if (loadHandle != null)
            {
                loadHandle(param);
            }
        }

        private IEnumerator OnLoadScene(int idx, LoadCallBack loadHandle, object param)
        {
            yield return YieldConst.WaitFor100ms;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            if (IsUseUnityScene)
            {
                AsyncOperation asyncUnityScene = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(idx, LoadSceneMode.Single);
                yield return asyncUnityScene;
            }

            if (loadHandle != null)
            {
                loadHandle(param);
            }
        }
    }
}