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

public class BannerAd : MonoBehaviour {

	public RawImage adIcon;
	public Text adTitle;
	public Text adDescription;
	public WG_AdURLButton adButton;
	public float refreshSeconds = 10.0f;

	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;
		StartCoroutine(this.CycleAds());
	}

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

		yield return new WaitForSeconds(this.refreshSeconds);
		StartCoroutine(CycleAds());
	}

	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.adIcon.texture = DownloadHandlerTexture.GetContent(uwr);
				this.adButton.callbackURL = ad.callbackURL;
				this.adButton.url = ad.storeURL;
				this.adTitle.text = ad.title;
				this.adDescription.text = ad.description;
			}
		}		
	}
}
