using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using System.Threading.Tasks;
using System;
using UnityEngine.Events;

public class AdsManager : MonoBehaviour
{
    private static AdsManager _instance;
    public static AdsManager instance => _instance;

    private BannerView bannerView;
    private InterstitialAd interstitial;
    private RewardedAd rewardedAd;



    [Header("Ids")]
    [SerializeField]private string bannerId;
    [SerializeField]private string interstitialId;
    [SerializeField]private string rewardedId;

    public UnityEvent onAwardEarned = new UnityEvent();


    public bool dontDestroyOnLoad=true;
    void Start()
    {
        _instance =this;
        if(dontDestroyOnLoad){DontDestroyOnLoad(gameObject);}

        MobileAds.Initialize(OnInit);        
    }

    void OnInit(InitializationStatus initStatus){
        // MessageDialog.instance.ShowMessage("Debug","Ads inited");
        DevLog.Log("Ads initiated, Loading ads now");
        Debug.Log("Google ads init,"+initStatus);
        Debug.Log("Loading ads now");
        rewardedAd = new RewardedAd(rewardedId);
        rewardedAd.OnUserEarnedReward += OnRewardedComplete;
        rewardedAd.OnAdFailedToLoad += OnRewardedFailed;
        rewardedAd.OnAdFailedToShow += OnRewardedFailed;
        rewardedAd.OnAdClosed += OnRewardCanceled;
        RequestBanner();
        LoadInterestitial();
        LoadRewarded();
    }


    void RequestBanner(){
        DevLog.Log("Loading Banner");
        try{
        bannerView = new BannerView(bannerId, AdSize.Banner, AdPosition.BottomLeft);
        AdRequest request = new AdRequest.Builder().Build();
        this.bannerView.LoadAd(request);
        }catch(Exception e){
            DevLog.Log(e.Message);
        }
    }

    public void LoadInterestitial(){
        DevLog.Log("Loading Interestitial");
        try{
        interstitial = new InterstitialAd(interstitialId);
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the interstitial with the request.
        interstitial.LoadAd(request);
        }catch(Exception e){
            DevLog.Log(e.Message);
        }
    }

    public void LoadRewarded(){
        DevLog.Log("Loading Rewarded");
        try{

        AdRequest request = new AdRequest.Builder().Build();
        this.rewardedAd.LoadAd(request);
        }catch(Exception e){
            DevLog.Log(e.Message);
        }
    }

    public async void ShowInterestitial(){
        DevLog.Log("Showing Interestitial");
        interstitial.Show();
        await Task.Delay(10000);
        LoadInterestitial();
    }
    public void ShowRewarded(){
        ShowRewarded(()=>{DevLog.Log("I Earned this, Back off");});
    }

    public async void ShowRewarded(UnityAction OnAwardEarned){
        // MessageDialog.instance.ShowMessage("Debug","Showing rewarded, is rewareded null? : " + (rewardedAd == null).ToString());
        DevLog.Log("Showing Rewarded, Rewarded ad null? : " + (rewardedAd==null).ToString());
                try{

        onAwardEarned.RemoveAllListeners();
        onAwardEarned.AddListener(OnAwardEarned);
        Debug.Log("Show Reward : is ad null? : " + (rewardedAd == null).ToString());
        
        if(!rewardedAd.IsLoaded()){
            Debug.Log("Ad not loaded, Loading now");
            LoadRewarded();
        }else{

        }
        while(!rewardedAd.IsLoaded()){
            await Task.Delay(500);
        }
        Debug.Log("Ad ready, showing now");

        this.rewardedAd.Show();
        Debug.Log("Ad shown");
        }catch(Exception e){
            DevLog.Log(e.Message);
        }

    }

    void OnRewardedComplete(object sender, EventArgs args){
        onAwardEarned.Invoke();
        LoadRewarded();
    }

    void OnRewardedFailed(object sender, EventArgs args){
        DevLog.Log("Ad failed to load");
        // MessageDialog.instance.ShowMessage("Sorry", "We couldn't Load the Ad right now. Please try again later.");
        LoadRewarded();

    }

    void OnRewardCanceled(object sender, EventArgs args){
        DevLog.Log("User canceled the ad");

        // MessageDialog.instance.ShowMessage("Failed", "You closed the Ad. Please watch the full ad to receive the gift");
        LoadRewarded();
    }
    
}
