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

namespace Guru
{
	public static partial class FirebaseUtil
	{
		public static FirebaseUser CurrentUser => FirebaseAuth.DefaultInstance.CurrentUser;
		
		private static readonly WaitForSeconds _wait = new WaitForSeconds(10);
		
		public static void AuthUser()
		{
			//FirebaseAuth获取用户验证并同步用户数据
			if (CurrentUser != null)
			{
				Log.I(LOG_TAG, "[Auth]之前验证没过期，CurrentUser: " + CurrentUser.UserId);
				return;
			}
			
			string authToken = IPMConfig.IPM_FIREBASE_TOKEN;
			Log.I(LOG_TAG, $"[Auth]AuthToken:{authToken}");
			if (string.IsNullOrEmpty(authToken) || !NetworkUtil.IsNetAvaliable)
			{
				CoroutineHelper.Instance.StartDelayed(_wait, AuthUser);
				return;
			}
			
			FirebaseAuth.DefaultInstance.SignInWithCustomTokenAsync(authToken)
				.ContinueWithOnMainThread(task =>
				{
					if (task.IsCanceled || task.IsFaulted)
					{
						Log.E(LOG_TAG,"[Auth] SignInWithCustomTokenAsync encountered an error: " + task.Exception);
						CoroutineHelper.Instance.StartDelayed(_wait, AuthUser);
					}
					else if (CurrentUser == null)
					{
						CoroutineHelper.Instance.StartDelayed(_wait, AuthUser);
					}
				});
		}
	}
}