using UnityEngine;

namespace ChillConnect
{
    public class SApplication : MonoBehaviour
    {
        public static bool IsAppQuit { get; private set; }

        public bool IsRestart { get; private set; }
        public int RestartCount { get; private set; }
        public bool IsAppFocus { get; private set; }
        public bool IsAppPause { get; private set; }
        public long LastFocusFlaseTime { get; private set; }

        public virtual void Init()
        {
            IsAppFocus = true;
        }

        public virtual void Enable()
        {
            CreateEnvironment();
        }

        private void CreateEnvironment()
        {
            AppObjConst.ApplicationGo = gameObject;
            AppObjConst.EngineSingletonGo = new GameObject(AppObjConst.EngineSingletonGoName);
            AppObjConst.EngineSingletonGo.SetParent(AppObjConst.FrameGo);
        }

        private void CloseApp()
        {
            if (UIManager.Instance != null)
            {
                UIManager.Instance.DisposeAllUI();
            }

            ModuleManager.Instance.DisposeAllModule();
            ManagerOfManager.Instance.DisposeAllManager();
            ManagerOfManager.Instance.Dispose();
        }

        private void OnApplicationFocus(bool focus)
        {
            IsAppFocus = focus;
            if (focus)
            {
                // MainThreadDispatcher.Instance.Dispatch(MainThreadMsg.App_Focus_True, focus);
                AppDispatcher.Instance.Dispatch(MainThreadMsg.App_Focus_True, focus);
            }
            else
            {
                LastFocusFlaseTime = DateTimeManager.Instance.GetServerCurrTimestamp();
                SaveData.SaveRankFunc(true);
                AppDispatcher.Instance.Dispatch(AppMsg.App_Focus_False, focus);
            }
        }

        private void OnApplicationPause(bool pause)
        {
            IsAppPause = pause;
            if (pause)
            {
                AppDispatcher.Instance.Dispatch(AppMsg.App_Pause_True, pause);
                AppDispatcher.Instance.Dispatch(MainThreadMsg.App_Focus_True, pause);
            }
            else
            {
                MainThreadDispatcher.Instance.Dispatch(MainThreadMsg.App_Pause_False, pause);
            }
        }

        private void OnApplicationQuit()
        {
            IsAppQuit = true;

            CloseApp();
            AppDispatcher.Instance.Dispatch(AppMsg.App_Quit);
            AssetBundle.UnloadAllAssetBundles(true);
        }
    }
}