

namespace Guru
{
	using System;
	using System.Collections;
	using Firebase.Messaging;
	using UnityEngine;
	
	public static partial class FirebaseUtil
	{
		private static int _messageRetry = 5;
		// public static bool? IsInitMessage;
		private static bool _isAutoFetchFcmToken = true;
		private static bool _isFetchOnce = false;

		public static void SetAutoFetchFcmToken(bool value)
		{
			_isAutoFetchFcmToken = value;
		}

		private static void InitializeMessage()
		{
			if (_isAutoFetchFcmToken)
			{
				StartFetchFcmToken();
			}
		}
		
		public static void StartFetchFcmToken()
		{
			if (_isFetchOnce) return;
			_isFetchOnce = true;
			
			FirebaseMessaging.TokenReceived += OnTokenReceived;
			FirebaseMessaging.MessageReceived += OnMessageReceived;
			GetFCMToken();
		}

		private static void GetFCMToken()
		{
			CoroutineHelper.Instance.StartCoroutine(CoroutineGetFCMToken());
		}

		private static IEnumerator CoroutineGetFCMToken()
		{
			var task = FirebaseMessaging.GetTokenAsync();
			while (!task.IsCompleted)
				yield return new WaitForEndOfFrame();

			if (task.IsFaulted || task.IsCanceled)
			{
				CoroutineHelper.Instance.StartDelayed(10, GetFCMToken);
			}
			else
			{
				Log.I(LOG_TAG, "GetTokenAsync Token: " + task.Result);
				if (IPMConfig.IPM_PUSH_TOKEN != task.Result || !IPMConfig.IS_UPLOAD_DEVICE_SUCCESS)
				{
					IPMConfig.IPM_PUSH_TOKEN = task.Result;
					UploadDeviceInfo();
				}
			}
		}

		private static void UploadDeviceInfo()
		{
			if (!NetworkUtil.IsNetAvailable)
			{
				double retryDelay = Math.Pow(2, _messageRetry);
				_messageRetry++;
				CoroutineHelper.Instance.StartDelayed((float) retryDelay, UploadDeviceInfo);
			}
			else
			{
				Log.I(LOG_TAG, "FirebaseMessage Send UploadDeviceInfo");
				//延时重试
				new DeviceInfoUploadRequest()
					.SetRetryTimes(1)
					.SetFailCallBack(() =>
					{
						double retryDelay = Math.Pow(2, _messageRetry);
						_messageRetry++;
						CoroutineHelper.Instance.StartDelayed((float) retryDelay, UploadDeviceInfo);
					}).Send();
			}
		}
		
		private static void OnTokenReceived(object sender, TokenReceivedEventArgs token)
        {
#if UNITY_IOS
	        DeviceUtil.SetiOSBadge();
#endif
        }

		public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
#if UNITY_IOS
	        DeviceUtil.SetiOSBadge();
#endif
        }
	}
}