using System;
using System.Collections.Generic;
using Firebase;
using Firebase.Analytics;
using Firebase.Extensions;

namespace Guru
{
	public static partial class FirebaseUtil
	{
		private static readonly string LOG_TAG = "Firebase";
		private static bool _isDebug = false;
		private static bool _isReady = false;
		public static bool IsReady => _isReady;
		
		public static DependencyStatus DependencyStatus = DependencyStatus.UnavailableOther;
		public static bool IsFirebaseInitialized => DependencyStatus == DependencyStatus.Available;
		public static Action<bool> onInitComplete;

		public static Action<bool> OnFirebaseAuthResult;
		public static Action<bool> OnUserAuthResult;
		
		
		
		public static void InitFirebase(Action callback, bool isDebug = false)
		{
			_isReady = false;
			_isDebug = isDebug;
			Analytics.InitAnalytics(); // 打点提前初始化
			
			// Loom.StartUp(); // 确保主线程开启
			
			// 初始化 Fireabse 依赖
			FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
				DependencyStatus = task.Result;
				if (DependencyStatus == DependencyStatus.Available)
				{
					_isReady = true;
					InitializeFirebaseComp();
					callback?.Invoke();
				} 
				else 
				{
					Log.E(LOG_TAG, "Could not resolve all Firebase dependencies: " + DependencyStatus);
				}
				onInitComplete?.Invoke(_isReady);
			});
		}
		private static void InitializeFirebaseComp()
		{
			InitCrashlytics();  // 老项目沿用此逻辑
			InitRemoteConfig();	// 老项目沿用此逻辑
			InitAdjustService();  // 初始化 Firebase 服务
			
			if (IPMConfig.IPM_UID.IsNullOrEmpty())
			{
				Log.I(LOG_TAG, "没有存储UID时，从中台获取匿名认证授权");
				//没有存储UID时，从中台获取匿名认证授权
				new AuthUserRequest()
					.SetRetryTimes(-1)
					.SetSuccessCallBack(() =>
					{
						OnUserAuthResult?.Invoke(true);
						AuthUser(InitializeMessage);
					}).SetFailCallBack(() =>
					{
						OnUserAuthResult?.Invoke(false);
					})
					.Send();
			}
			else
			{
				InitializeMessage();
				int currentTimeStamp = TimeUtil.GetCurrentTimeStampSecond();
				if(currentTimeStamp - IPMConfig.IPM_TOKEN_TIME >= IPMConfig.TOKEN_VALID_TIME)
				{
					//中台Token失效，从中台重新获取Token
					new RefreshTokenRequest().SetRetryTimes(-1).Send();
				}
				
				if(currentTimeStamp - IPMConfig.IPM_FIREBASE_TOKEN_TIME >= IPMConfig.FIREBASE_TOKEN_VALID_TIME)
				{
					//中台firebaseToken失效，从中台重新获取firebaseToken
					new RefreshFirebaseTokenRequest()
						.SetRetryTimes(-1)
						.SetSuccessCallBack(()=> AuthUser(InitializeMessage))
						.Send();
				}
				else
				{
					AuthUser(InitializeMessage);
				}
			}
		}

		#region 启动 Adjust 服务
		
		/// <summary>
		/// 启动 Adjust 服务
		/// </summary>
		private static void InitAdjustService()
		{
			FirebaseAnalytics.GetAnalyticsInstanceIdAsync()
				.ContinueWithOnMainThread(task =>
				{
					if (task.IsCompleted && !string.IsNullOrEmpty(task.Result)) 
					{
						// 保存本地ID备份
						string fid = task.Result;
						IPMConfig.FIREBASE_ID = fid; // 保存FirebaseID
					}
					else
					{
						UnityEngine.Debug.LogError($"Fetch FirebaseID failed on start!");
					}
					
					// 启动 AdjustService
					string appToken = GuruSettings.Instance.AdjustSetting?.GetAppToken() ?? "";
					string fbAppId = GuruSettings.Instance.IPMSetting.FacebookAppId;
					AdjustService.StartService(appToken, fbAppId);  
				});
			
			
		}
		

		#endregion

		
		
	}
}