using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using FairyGUI;
using Fantasy;
using Fantasy.Async;
using NBC;
using NBC.Asset;
using NBF.Fishing2;
using SimpleJSON;
using UnityEngine;
using Log = Fantasy.Log;

namespace NBF
{
    public class Game : MonoBehaviour
    {
        public static Game Instance { get; private set; }


        private static Scene _scene;
        public static Scene Main => _scene;

        private static cfg.Tables _tables;
        public static cfg.Tables Tables => _tables;
        private static event Action OnInitialized;
        public static event Action OnUpdate;
        public static event Action OnLateUpdate;
        public static event Action OnFixedUpdate;
        public static event Action OnApplicationQuitAction;
        public static event Action OnApplicationPauseAction;


        public static void SetInitCallback(GameObject root, Action callback = null)
        {
            if (Instance != null) return;
            root.AddComponent<Game>();
            OnInitialized += callback;
            // NBC_Fantasy_EntitySystemRegistrar
        }

        private void Awake()
        {
            Instance = this;
        }

        private void Start()
        {
            StartAsync().Coroutine();
        }

        private void Update()
        {
            OnUpdate?.Invoke();
        }

        private void LateUpdate()
        {
            OnLateUpdate?.Invoke();
        }

        private void FixedUpdate()
        {
            OnFixedUpdate?.Invoke();
        }

        private void OnApplicationQuit()
        {
            OnApplicationQuitAction?.Invoke();
        }

        private void OnApplicationPause(bool pauseStatus)
        {
            OnApplicationPauseAction?.Invoke();
        }

        private void OnDestroy()
        {
            _scene?.Dispose();
        }

        private async FTask StartAsync()
        {
            var task = Assets.Initialize();
            await task.Task;
            // // 初始化框架
            // var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            // // List<System.Reflection.Assembly> loadAssemblies = new List<System.Reflection.Assembly>();
            // foreach (var assembly in assemblies)
            // {
            //     // 跳过系统程序集以提高性能（可选）
            //     if (IsSystemAssembly(assembly))
            //         continue;
            //     loadAssemblies.Add(assembly);
            // }

            gameObject.AddComponent<Settings>();

            // 1. 初始化 Fantasy 框架
            await Fantasy.Platform.Unity.Entry.Initialize();

            // 2. 创建一个 Scene (客户端场景)
            // Scene 是 Fantasy 框架的核心容器,所有功能都在 Scene 下运行
            // SceneRuntimeMode.MainThread 表示在 Unity 主线程运行
            _scene = await Scene.Create(SceneRuntimeMode.MainThread);

            LoadData();
            InitLanguage();
            InitUI();

            OnInitialized?.Invoke();
        }


        #region Config

        private void LoadData()
        {
            // 一行代码可以加载所有配置。 cfg.Tables 包含所有表的一个实例字段。
            _tables = new cfg.Tables(LoadJson);
        }

        private static JSONNode LoadJson(string file)
        {
            // var json = File.ReadAllText($"{your_json_dir}/{file}.json", System.Text.Encoding.UTF8);
            //Assets/ResRaw/config/tb/tbbait.json
            var jsonAsset = Assets.Load<TextAsset>($"Assets/ResRaw/config/tb/{file}.json");
            return JSON.Parse(jsonAsset.text);
        }
        #endregion

        #region 多语言

        private void InitLanguage()
        {
            // var map = LanguageConst.languageMap;

            Lan.Inst.AddLanguageModule((int)LanguageModuleType.Text, new LanguageText());
            Lan.Inst.AddLanguageModule((int)LanguageModuleType.Image, new LanguageImage());
            Lan.Inst.AddLanguageModule((int)LanguageModuleType.Font, new LanguageFont());

            foreach (var key in LanguageConst.languageMap.Keys)
            {
                Lan.Inst.AddLanguage(key);
            }

            UI.Inst.SetUILanguage<UILangeageConfig>();
            Lan.Inst.AutoUseLanguage();
        }

        #endregion

        #region UI

        private void InitUI()
        {
            UI.Inst.SetUITween<UITweenConfig>();
            Binder.BindAll();
            UIObjectFactory.SetLoaderExtension(typeof(XGLoader));
            UIConst.UIPackRootUrl = UIDef.UIRoot;
            UIConfig.verticalScrollBar = "ui://6hgkvlauoomej";
            UIConfig.defaultFont = "AlibabaPuHuiTi-3-Medium";
            UI.Inst.SetUILanguage<UILangeageConfig>();
            UIConfig.modalLayerColor = new Color(0, 0, 0, 0.92f);
            AddUIPackages();
        }

        private void AddUIPackages()
        {
            UI.Inst.AddPackage("Common/Common");
            UI.Inst.AddPackage("CommonNew/CommonNew");
            UI.Inst.AddPackage("CommonFlag/CommonFlag");
            UI.Inst.AddPackage("CommonIcon/CommonIcon");
        }

        #endregion

        // 判断是否是系统程序集（可选优化）
        private static bool IsSystemAssembly(System.Reflection.Assembly assembly)
        {
            string assemblyName = assembly.FullName;
            return assemblyName.StartsWith("System") ||
                   assemblyName.StartsWith("Microsoft.") ||
                   assemblyName.StartsWith("UnityEngine") ||
                   assemblyName.StartsWith("UnityEditor") ||
                   assemblyName.StartsWith("mscorlib") ||
                   assemblyName.StartsWith("netstandard") ||
                   assemblyName.StartsWith("nunit.") ||
                   assemblyName.StartsWith("Unity.");
        }
    }
}