using System.Collections.Generic;
using UnityEngine;

namespace BingoBrain.Core
{
    public sealed class SceneBoardk : BaseInterfaceManager<SceneBoardk>
    {
        public const int DefaultMainSceneIdx = 0;

        private Dictionary<int, BaseScene> sceneDict = new();
        private BaseScene m_currScene;

        public void AddScene(BaseScene scene)
        {
            if (!sceneDict.ContainsKey(scene.SceneIdx))
            {
                sceneDict[scene.SceneIdx] = scene;
            }
        }

        public void InitialMain(object param = null)
        {
            if (sceneDict.Count == 0) return;

            BaseScene scene = GetScene(DefaultMainSceneIdx);
            if (SetScene(scene))
            {
                SceneSwitch.Instance.SwitchInitialScene(DefaultMainSceneIdx, scene.SwchSneCote, param);
            }
        }

        public void SwitchScene(int sceneIdx, object param = null)
        {
            BaseScene scene = GetScene(sceneIdx);
            if (SetScene(scene))
            {
                UI.Instance.SwitchSceneCloseAllUI();
                SceneSwitch.Instance.SwitchScene(sceneIdx, scene.SwchSneCote, param);
            }
        }

        private bool SetScene(BaseScene scene)
        {
            if (scene == null)
            {
                Debug.LogError("[SceneMgr]Set Scene Failed: Scene Is Null");
                return false;
            }
            else if (scene == m_currScene)
            {
                Debug.LogError("[SceneMgr]Set Scene Failed: Switch Repetitive Scene");
                return false;
            }

            if (m_currScene != null)
            {
                m_currScene.Leave();
            }

            m_currScene = scene;
            m_currScene.Enter();
            return true;
        }

        private BaseScene GetScene(int sceneIdx)
        {
            BaseScene scene = null;
            if (!sceneDict.TryGetValue(sceneIdx, out scene))
            {
                Debug.LogError("[SceneMgr]No Have This Scene: " + sceneIdx);
            }

            return scene;
        }

        public override void Dispose()
        {
            base.Dispose();
            foreach (BaseScene scene in sceneDict.Values)
            {
                scene.Dispose();
            }

            sceneDict.Clear();
            sceneDict = null;
        }
    }
}