using System;
using UnityEngine;

namespace XGame.Framework
{
    /// <summary>
    /// 入口 
    /// </summary>
    internal static class Entrance
    {
        /// <summary>
        /// 程序入口
        /// </summary>
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        internal static void Access()
        {
            Profiler.BeginSample(typeof(Entrance), "Log.Initialize");
            Log.Initialize();
            Profiler.EndSample();

#if UNITY_EDITOR
            Profiler.BeginSample(typeof(Entrance), "IsInvalid");
            var errorCode = IsInvalid();
            if (errorCode != 0)
            {
                return;
            }
            Profiler.EndSample();
#endif

            Profiler.BeginSample(typeof(Entrance), "AppManager.Initialize");
            AppManager.Initialize();
            Profiler.EndSample();

        }
#if UNITY_EDITOR
        private static int IsInvalid()
        {
            var config = XGameConfig.Load();
            if (config == null)
            {
                Log.Error($"Entrance error: 找不到 XGameConfig.asset.");
                return -1;
            }
            var launchSceneName = config.launchSceneName;
            var gameLogicTypeName = config.gameLogicTypeName;
            XGameConfig.Unload(config);
            if (string.IsNullOrEmpty(launchSceneName))
            {
                Log.Error($"Entrance error: XGameConfig.asset 没有设置启动场景.");
                return -2;
            }
            if (!UnityEngine.SceneManagement.SceneManager.GetActiveScene().name.Equals(launchSceneName))
            {
                Log.Error($"Entrance error: XGameConfig.asset 启动场景没有激活.");
                return -3;
            }
            if (string.IsNullOrEmpty(gameLogicTypeName))
            {
                Log.Error($"Entrance error: XGameConfig.asset 没有设置启动脚本.");
                return -4;
            }
            if (Type.GetType(gameLogicTypeName) == null)
            {
                Log.Error($"Entrance error: XGameConfig.asset 找不到启动脚本. Type:{gameLogicTypeName}");
                return -5;
            }
            //var assembly = System.Reflection.Assembly.Load(config.launchAssemblyName);
            //assembly.GetType(gameLogicTypeName);

            return 0;
        }
#endif

    }
}

