using System;
using System.Collections;
using Firebase.Messaging;
using UnityEngine;

namespace Guru
{
	public static partial class FirebaseUtil
	{
		private static int _messageRetry = 5;
		public static bool? IsInitMessage;
		
		public static void InitializeMessage()
		{
			FirebaseMessaging.TokenReceived += OnTokenReceived;
			FirebaseMessaging.MessageReceived += OnMessageReceived;
			GetFCMToken();
			IsInitMessage = true;
		}

		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(_wait, 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.IsNetAvaliable)
			{
				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, Firebase.Messaging.TokenReceivedEventArgs token)
        {
#if UNITY_IOS
	        DeviceUtil.SetiOSBadge();
#endif
        }

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