﻿using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using UnityEngine.UI;

public class InterstitialAd : MonoBehaviour {

	public RawImage adImage;
	public WG_AdURLButton adButton;

	private WG_GameAd[] ads = null;

	void OnEnable() {
		WG_FAN.FetchAdsComplete += SetAdList;
	}

	void OnDisable() {
		WG_FAN.FetchAdsComplete -= SetAdList;
	}

	void SetAdList(WG_GameAd[] ads) {
		this.ads = ads;
		this.ShowAd();
	}

	public void ShowAd() {
		if (this.ads != null && this.ads.Length > 0) {
			WG_GameAd ad = this.ads[Random.Range(0, ads.Length)];
			if (ad != null) {
				StartCoroutine(SetAdContent(ad.imageURL, ad));
			}
		}
	}

	public IEnumerator SetAdContent(string imageURL, WG_GameAd ad)
	{
		using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(imageURL))
		{
			yield return uwr.SendWebRequest();

			if (uwr.isNetworkError || uwr.isHttpError)
			{
				Debug.Log(uwr.error);
			}
			else
			{
				this.adImage.texture = DownloadHandlerTexture.GetContent(uwr);
				this.adButton.callbackURL = ad.callbackURL;
				this.adButton.url = ad.storeURL;
			}
		}
	}
}
