using System;
using System.Collections.Generic;
using UnityEngine;

namespace mgaia.Utils
{
	/// <summary>
	/// Extensões da classe Application da Unity
	/// </summary>
	/// <owner>Victor</owner>
	public static class ApplicationExtensions
	{
		/// <summary>
		/// Abre uma intent externa caso o device consiga responder ela, caso contrario abre uma URL de fallback enviada
		/// </summary>
		public static void MakeExternalIntent(string packageIdentifier, string externalUrlCall, string fallbackBrowserUrl)
		{
#if UNITY_ANDROID
			if (CheckIfPackageExists(packageIdentifier))
			{
				OpenURL(externalUrlCall);
			}
			else
			{
				OpenURL(fallbackBrowserUrl);
			}
#elif UNITY_IPHONE
			//FEIO PRA KCT

			float startTime = Time.timeSinceLevelLoad;

			OpenURL(externalUrlCall);
			
			if (Time.timeSinceLevelLoad - startTime <= 1f)
			{
				OpenURL(fallbackBrowserUrl);
			}
#else
            OpenURL(fallbackBrowserUrl);
#endif
		}

#if UNITY_ANDROID
		/// <summary>
		/// Checa se um pacote está instalado no aparelho
		/// </summary>
		public static bool CheckIfPackageExists(string packageIdentifier)
		{
			AndroidJavaClass up = new AndroidJavaClass(Constants.UNITY_3D_PACKAGE_IDENTIFIER);
			AndroidJavaObject ca = up.GetStatic<AndroidJavaObject>("currentActivity");
			AndroidJavaObject packageManager = ca.Call<AndroidJavaObject>("getPackageManager");
			AndroidJavaObject appList = packageManager.Call<AndroidJavaObject>("getInstalledPackages", 0);

			int size = appList.Call<int>("size");

			for (int idx = 0; idx < size; idx++)
			{
				AndroidJavaObject appInfo = appList.Call<AndroidJavaObject>("get", idx);

				string packageNew = appInfo.Get<string>("packageName");
				if (packageNew.CompareTo(packageIdentifier) == 0)
				{
					return true;
				}

			}

			return false;
		}
#endif

        /// <summary>
        /// Testa se o jogo está rodando em um aparelho da Amazon
        /// </summary>
        public static bool IsAmazonDevice()
        {
            return SystemInfo.deviceModel.ToUpper().Contains(Constants.AMAZON_IDENTIFIER_STRING);
        }

		/// <summary>
		/// Abre uma URL no device
		/// </summary>
		private static void OpenURL(string url)
		{
			Application.OpenURL(url);
		}
	}
}