using System.Collections.Generic;

namespace ChillConnect
{
    public sealed class SceneManager : BaseInterfaceManager<SceneManager>
    {
        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))
            {
                SceneSwitchManager.Instance.SwitchInitialScene(DefaultMainSceneIdx, scene.SwitchSceneComplete, param);
            }
        }

        public void SwitchScene(int sceneIdx, object param = null)
        {
            BaseScene scene = GetScene(sceneIdx);
            if (SetScene(scene))
            {
                UIManager.Instance.SwitchSceneCloseAllUI();
                SceneSwitchManager.Instance.SwitchScene(sceneIdx, scene.SwitchSceneComplete, param);
            }
        }

        private bool SetScene(BaseScene scene)
        {
            if (scene == null)
            {
                return false;
            }

            if (scene == m_currScene)
            {
                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))
            {
            }

            return scene;
        }

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

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