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

namespace BingoBrain.Core
{
    public sealed class SceneSwitch : BaseUnity<SceneSwitch>
    {
        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 vbadConst.Time10ms;

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

        private IEnumerator OnLoadScene(int idx, LoadCallBack loadHandle, object param)
        {
            yield return vbadConst.WaitFor100ms;
            
            GC.Collect();
            GC.WaitForPendingFinalizers();

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

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