using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace CGAStudio.WebPortal
{
///
/// Drop-in Unity WebGL Bridge for CGA Shared Economy & Google H5 Rewarded Ads.
/// Pair with Assets/Plugins/WebGL/CGAPortal.jslib and include:
/// in your WebGL index.html.
///
public class CGAPortalBridge : MonoBehaviour
{
public static CGAPortalBridge Instance { get; private set; }
public int Balance { get; private set; }
public bool IsVipAdFree { get; private set; }
public event Action WalletUpdated;
public event Action RewardedAdCompleted;
public event Action RewardedAdDismissed;
#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport("__Internal")] private static extern void CGAPortal_Init(string gameObjectName);
[DllImport("__Internal")] private static extern void CGAPortal_EarnCoins(string gameSlug, int amount, string reason, string refId);
[DllImport("__Internal")] private static extern void CGAPortal_SpendCoins(string gameSlug, int amount, string reason, string refId);
[DllImport("__Internal")] private static extern void CGAPortal_ShowRewardedAd(string gameSlug, string placement);
[DllImport("__Internal")] private static extern void CGAPortal_ShowInterstitial(string placement);
[DllImport("__Internal")] private static extern void CGAPortal_OpenShop(string tab);
#endif
[Serializable]
private class WalletDto
{
public int balance;
public bool vip_ad_free;
}
private void Awake()
{
if (Instance != null) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_Init(gameObject.name);
#endif
}
public void EarnCoins(string gameSlug, int amount, string reason, string refId = "")
{
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_EarnCoins(gameSlug, amount, reason, refId);
#endif
}
public void SpendCoins(string gameSlug, int amount, string reason, string refId = "")
{
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_SpendCoins(gameSlug, amount, reason, refId);
#endif
}
public void ShowRewardedAd(string gameSlug, string placement = "reward_coins")
{
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_ShowRewardedAd(gameSlug, placement);
#else
RewardedAdCompleted?.Invoke("{}");
#endif
}
public void ShowInterstitial(string placement = "between_levels")
{
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_ShowInterstitial(placement);
#endif
}
public void OpenShop(string tab = "packs")
{
#if UNITY_WEBGL && !UNITY_EDITOR
CGAPortal_OpenShop(tab);
#endif
}
// Callbacks invoked from CGAPortal.jslib via SendMessage
public void OnCGAWalletUpdated(string json)
{
var dto = JsonUtility.FromJson(json);
if (dto != null)
{
Balance = dto.balance;
IsVipAdFree = dto.vip_ad_free;
WalletUpdated?.Invoke(Balance, IsVipAdFree);
}
}
public void OnCGARewardedAdComplete(string json) => RewardedAdCompleted?.Invoke(json);
public void OnCGARewardedAdDismissed(string _) => RewardedAdDismissed?.Invoke();
}
}