using System.Threading;
using UnityEngine;
using UnityEngine.Events;

namespace WS
{
    ///<summary>启动器基类</summary>
    public abstract class Init : MonoBehaviour
    {
        private void Awake()
        {
            //网络消息回调主线程
            SynchronizationContext.SetSynchronizationContext(
                OneThreadSynchronizationContext.Instance
            );
            //限制帧数
            Application.targetFrameRate = 90;
#if UNITY_EDITOR
            Log.IsEditor();
#endif

#if DEBUG_MODEL
            Log.IsDebug();
            GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/Reporter/Reporter"));
#endif

#if DEBUG_LOG
            Log.IsWrite();
#endif
            //设置为不销毁
            DontDestroyOnLoad(gameObject);

            //赋值Init物体
            Game.Init = this.transform;

            //初始化框架
            Game.EventSystem.LoadSystem(typeof(Init).Assembly);

            //计时/协程
            Game.Scene.AddComponent<TimerComponent>();
            //音效
            Game.Scene.AddComponent<VoiceManager>();
            //Game对象池
            Game.Scene.AddComponent<GamePoolManager>();
            //MVC代理
            Game.Scene.AddComponent<FacadeComponent>();
            //场景
            Game.Scene.AddComponent<SceneComponent>();
            //HTTP请求
            Game.Scene.AddComponent<RequestComponent>();
            //全局事件
            Game.Scene.AddComponent<EventComponent>();
        }

        private void Start()
        {
            //调用子类初始化
            Initialize();
        }

        ///<summary>初始化</summary>
        public abstract void Initialize();

        ///<summary>循环</summary>
        public virtual void OnUpdate() { }

        ///<summary>退出</summary>
        public void Quit(UnityAction OnCallback = null)
        {
            OnCallback?.Invoke();
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }

        private void Update()
        {
            OneThreadSynchronizationContext.Instance.Update();
            Game.EventSystem.Update();
            OnUpdate();
        }

        private void FixedUpdate()
        {
            Game.EventSystem.FixedUpdate();
        }

        private void LateUpdate()
        {
            Game.EventSystem.LateUpdate();
        }
    }
}
