using System;
using System.Threading;
using CommandLine;
using Sirenix.OdinInspector;
using UnityEngine;
using YooAsset;

namespace ET
{
	public class Init: MonoBehaviour
	{
		private void Awake()
		{
#if UNITY_STANDALONE_WIN
			Screen.SetResolution(540, 960, false);
#endif
#if UNITY_EDITOR
			//Editor模式下去掉debug浮窗插件
			var debugObj = GameObject.Find("IngameDebugConsole");
            if (debugObj != null)
            {
                GameObject.Destroy(debugObj);
            }
#endif
            DontDestroyOnLoad(gameObject);

			//登陆过程限定帧率为30fps
			Application.targetFrameRate = (int)FPS.Login;

			AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
			{
				Log.Error(e.ExceptionObject.ToString());
			};
				
			Game.AddSingleton<MainThreadSynchronizationContext>();

			// 命令行参数
			string[] args = "".Split(" ");
			Parser.Default.ParseArguments<Options>(args)
				.WithNotParsed(error => throw new Exception($"命令行格式错误! {error}"))
				.WithParsed(Game.AddSingleton);
			
			Game.AddSingleton<TimeInfo>();
			Game.AddSingleton<Logger>().ILog = new UnityLogger();
			Game.AddSingleton<ObjectPool>();
			Game.AddSingleton<IdGenerater>();
			Game.AddSingleton<EventSystem>();
			Game.AddSingleton<TimerComponent>();
			Game.AddSingleton<CoroutineLockComponent>();
			
			ETTask.ExceptionHandler += Log.Error;

			Game.AddSingleton<CodeLoader>().Start();
		}

		private void Update()
		{
			Game.Update();
		}

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

		private void OnApplicationQuit()
		{
			Game.Close();
		}
	}
}