using System;
#if UNITY_WEBGL && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif
using UnityEngine;
using AOT;

namespace Arkadium
{
	public interface IArkadiumAds
	{
		void ShowInterstitialAd(int duration, Action<bool> cb);
		void ShowRewardAd(int duration, Action<int> cb);
		void ShowBannerAd(string elementId, params string[] bannerSizes);
	}

	public class ArkadiumAds : IArkadiumAds
	{
		public const string AD_300x250 = "AD_300x250";
		public const string AD_250x250 = "AD_250x250";
		public const string AD_336x280 = "AD_336x280";
		public const string AD_300x600 = "AD_300x600";
		public const string AD_728x90 = "AD_728x90";
		public const string AD_970x90 = "AD_970x90";
		public const string AD_970x250 = "AD_970x250";
		public const string AD_320x50 = "AD_320x50";
		public const string AD_320x100 = "AD_320x100";
		public const string AD_468x60 = "AD_468x60";
		public const string AD_160x600 = "AD_160x600";
		
	#if UNITY_WEBGL && !UNITY_EDITOR
		[DllImport("__Internal")]
		private static extern void _ShowInterstitialAd(int duration, Action<int> cb);
		[DllImport("__Internal")]
		private static extern void _ShowRewardAd(int duration, Action<int> cb);
		[DllImport("__Internal")]
		private static extern void _ShowBannerAd(string elementId, string bannerSizes);
	#else
		private void _ShowInterstitialAd(int duration, Action<int> cb) { cb?.Invoke(1); }
		private void _ShowRewardAd(int duration, Action<int> cb) { cb?.Invoke(1); }
		private void _ShowBannerAd(string elementId, string bannerSizes) { }
	#endif

		private static Action<int> _showRewardAdCb;
		private static Action<bool> _showInterstitialAdCb;

		public void ShowInterstitialAd(int duration, Action<bool> cb) {
			_showInterstitialAdCb = cb;
			_ShowInterstitialAd(duration, ShowInterstitialAdCb);
		}
		
		public void ShowRewardAd(int duration, Action<int> cb) {
			_showRewardAdCb = cb;
			_ShowRewardAd(duration, ShowRewardAdCb);
		}
		
		// TODO enforce proper type
		public void ShowBannerAd(string elementId, params string[] bannerSizes) {
			var serializedBannerSizes = BasicJSON.FromStringArray(bannerSizes);
			_ShowBannerAd(elementId, serializedBannerSizes);
		}

		[MonoPInvokeCallback(typeof(Action<int>))]
		private static void ShowInterstitialAdCb(int result) {
			ArkadiumSDK.Instance.Log($"Show interstitial ad returned {result}");
			_showInterstitialAdCb?.Invoke(result == 1);
			_showInterstitialAdCb = null;
		}
	
		[MonoPInvokeCallback(typeof(Action<int>))]
		private static void ShowRewardAdCb(int result) {
			ArkadiumSDK.Instance.Log($"Show reward ad returned {result}");
			_showRewardAdCb?.Invoke(result);
			_showRewardAdCb = null;
		}
}
}
