using Firebase.Auth;
using Firebase.Extensions;
using UnityEngine;

namespace Guru
{
	using System;
	public static partial class FirebaseUtil
	{
		public static FirebaseUser CurrentUser => FirebaseAuth.DefaultInstance.CurrentUser;
		
		private static readonly WaitForSeconds _wait = new WaitForSeconds(10);
		
		public static void AuthUser(Action onSuccessHandler = null)
		{
			//FirebaseAuth获取用户验证并同步用户数据
			if (CurrentUser != null)
			{
				Log.I(LOG_TAG, $"[Auth] user exists，UserId:{CurrentUser.UserId}");
				OnFirebaseAuthResult?.Invoke(true);
				onSuccessHandler?.Invoke();
				return;
			}
			
			string authToken = IPMConfig.IPM_FIREBASE_TOKEN;
			Log.I(LOG_TAG, $"[Auth] Firebase Token:{authToken}");
			if (string.IsNullOrEmpty(authToken) || !NetworkUtil.IsNetAvaliable)
			{
				CoroutineHelper.Instance.StartDelayed(_wait, ()=> AuthUser(onSuccessHandler));
				OnFirebaseAuthResult?.Invoke(false);
				return;
			}
			
			FirebaseAuth.DefaultInstance.SignInWithCustomTokenAsync(authToken)
				.ContinueWithOnMainThread(task =>
				{
					// ----- Task failed ----- 
					if (task.IsCanceled || task.IsFaulted)
					{
						Log.E(LOG_TAG,"[Auth] SignInWithCustomTokenAsync encountered an error: " + task.Exception);
						OnFirebaseAuthResult?.Invoke(false);
						CoroutineHelper.Instance.StartDelayed(_wait, () => AuthUser(onSuccessHandler));
						return;
					}
					// ----- User is NULL ----- 
					if (CurrentUser == null)
					{
						OnFirebaseAuthResult?.Invoke(false);
						CoroutineHelper.Instance.StartDelayed(_wait, ()=> AuthUser(onSuccessHandler));
						return;
					}
					// ----- Success ----- 
					OnFirebaseAuthResult?.Invoke(true); // 最后判定是成功的
					onSuccessHandler?.Invoke();
				});
		}
	}
}