using System.Threading;
using UnityEngine;
using XGame.Framework.Asyncs;
using XGame.Framework.ThreadScheduler;

namespace XGame.Framework
{
    public partial class AppManager
    {
        private static IAppManager _instance;
        private static IAppManager Instance => _instance ?? (_instance = new AppManager());


        /// <summary>
        /// 客户端当前帧数(非线程安全) 注意: 热重启不会归零
        /// </summary>
        public static long FrameCount { get; internal set; }
        /// <summary>
        /// 主线程ID
        /// </summary>
        public static readonly int MainThreadId = Thread.CurrentThread.ManagedThreadId;
        /// <summary>
        /// 根节点
        /// </summary>
        public static Transform Root => _instance?.Root;

        internal static void Initialize()
        {
            Instance.Restart();
        }
        /// <summary>
        /// 启动
        /// </summary>
        static public void Start()
        {
            _instance?.Start();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        static public IAsync Close()
        {
            AsyncGroup group = new AsyncGroup();
            FrameworkSchedulers.RunOnMainThread(() =>
            {
                var closeAsync = _instance?.Close();
                closeAsync?.Join(group);
                group.End();
            });
            return group;
        }

        /// <summary>
        /// 重启
        /// </summary>
        /// <returns></returns>
        static public IAsync Restart()
        {
            AsyncGroup group = new AsyncGroup();
            FrameworkSchedulers.RunOnMainThread(() =>
            {
                var restartAsync = _instance?.Restart();
                restartAsync?.Join(group);
                group.End();
            });
            return group;
        }

        /// <summary>
        /// 退出游戏
        /// </summary>
        static public void Quit()
        {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            UnityEngine.Application.Quit();
#endif
        }
    }
}
