using System;
using System.Collections;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using UnityEngine;

public class AdsManager : MonoBehaviour
{
    // Start is called before the first frame update

    public static AdsManager instance;
    void Awake(){
        if(instance!= null){Destroy(gameObject);}
        instance = this;
    }

    const string intAdId = "ca-app-pub-3966734202864173/1197808629";
    const string rewardedAdId = "ca-app-pub-3966734202864173/3725853326";
    void Start()
    {
        DontDestroyOnLoad(gameObject);
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize(initStatus => { Debug.Log("admob Init status : " + initStatus.ToString());});

        StartCoroutine(ReloadAds(true));
    }

     private InterstitialAd interstitialAd;

  /// <summary>
  /// Loads the interstitial ad.
  /// </summary>
  public void LoadInterstitialAd()
  {
      // Clean up the old ad before loading a new one.
      if (interstitialAd != null)
      {
            interstitialAd.Destroy();
            interstitialAd = null;
      }

      Debug.Log("Loading the interstitial ad.");

      // create our request used to load the ad.
      var adRequest = new AdRequest.Builder()
              .AddKeyword("unity-admob-sample")
              .Build();

      // send the request to load the ad.
      InterstitialAd.Load(intAdId, adRequest,
          (InterstitialAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("interstitial ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Interstitial ad loaded with response : "
                        + ad.GetResponseInfo());

              interstitialAd = ad;
          });


    }

    public void ShowIntAd()
    {
        if (interstitialAd != null && interstitialAd.CanShowAd())
        {
            Debug.Log("Showing interstitial ad.");
            interstitialAd.Show();
        }
        else
        {
            Debug.LogError("Interstitial ad is not ready yet.");
        }
        StartCoroutine(ReloadAds(false));

    }

    
    private RewardedAd rewardedAd;

    /// <summary>
    /// Loads the rewarded ad.
    /// </summary>
    public void LoadRewardedAd()
    {
        // Clean up the old ad before loading a new one.
        if (rewardedAd != null)
        {
                rewardedAd.Destroy();
                rewardedAd = null;
        }

        Debug.Log("Loading the rewarded ad.");

        // create our request used to load the ad.
        var adRequest = new AdRequest.Builder().Build();

        // send the request to load the ad.
        RewardedAd.Load(rewardedAdId, adRequest,
            (RewardedAd ad, LoadAdError error) =>
            {
                // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    Debug.LogError("Rewarded ad failed to load an ad " +
                                    "with error : " + error);
                    return;
                }

                Debug.Log("Rewarded ad loaded with response : "
                            + ad.GetResponseInfo());

                rewardedAd = ad;

                rewardedAd.OnAdPaid += OnRewardSuccess;
            });
    }

    private void OnRewardSuccess(AdValue obj)
    {
        GameManager.AdWatched();
    }

    public void ShowRewardedAd()
    {
        const string rewardMsg =
            "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

        if (rewardedAd != null && rewardedAd.CanShowAd())
        {
            rewardedAd.Show((Reward reward) =>
            {
                // TODO: Reward the user.
                Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
            });
        }

        StartCoroutine(ReloadAds(true));
    }


    IEnumerator ReloadAds(bool rewarded){
        yield return new WaitForSeconds(2);
        LoadInterstitialAd();
        if(rewarded){
            LoadRewardedAd();
        }
    }


}
