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

public class WG_FAN : MonoBehaviour {

	public delegate void FetchedAdsHandler(WG_GameAd[] ads);
	public static event FetchedAdsHandler FetchAdsComplete;

	public string androidPackageKey = "test_android_key";
	public string iOSPackageKey = "test_ios_key";
	public string pcPackageKey = "test_steam_key";

	private WG_GameAd[] adList;
	private bool loaded {get; set;}

	public static WG_FAN instance;
	
	void Awake() {
		if (WG_FAN.instance == null) {
			WG_FAN.instance = this;
			WG_FAN.instance.loaded = false;
			DontDestroyOnLoad(this.gameObject);
		}
		else if (WG_FAN.instance != this) {
			Destroy(this.gameObject);
		}
	}

	public void FetchAds() {
		this.loaded = false;
		string packageKey = this.pcPackageKey;
		if (Application.platform == RuntimePlatform.Android) {
			packageKey = this.androidPackageKey;
		}
		else if (Application.platform == RuntimePlatform.IPhonePlayer) {
			packageKey = this.iOSPackageKey;
		}

		//WWW request = new WWW("https://wirthwhilegaming.com/api/ads/get?package_key="+packageKey);
		//StartCoroutine(WaitForAds(request));
		string url = "https://wirthwhilegaming.com/api/ads/get?package_key=" + packageKey;
		StartCoroutine(GetRequest(url));
	}

	IEnumerator GetRequest(string uri)
	{
		using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
		{
			yield return webRequest.SendWebRequest();

			if (webRequest.isNetworkError)
			{
				Debug.Log("Web request error: " + webRequest.error);
			}
			else
			{
				this.loaded = true;
				JSONNode json = JSON.Parse(webRequest.downloadHandler.text);
				if (json["ads"] != null)
				{
					this.adList = new WG_GameAd[json["ads"].Count];
					JSONArray adArray = json["ads"].AsArray;
					int i = 0;
					foreach (JSONNode ad in adArray)
					{
						adList[i] = new WG_GameAd(
							ad["ref"],
							ad["title"],
							ad["description"],
							ad["store_url"],
							ad["web_url"],
							ad["callback_url"],
							ad["image_url"],
							ad["icon_url"]
						);

						i++;
					}

					if (FetchAdsComplete != null)
					{
						FetchAdsComplete(adList);
					}
				}
			}
		}
	}

	/*public IEnumerator WaitForAds(WWW www){
		yield return www;
		
		if (string.IsNullOrEmpty(www.error)) {
			this.loaded = true;
			JSONNode json = JSON.Parse(www.text);
			if (json["ads"] != null) {
				this.adList = new WG_GameAd[json["ads"].Count];
				JSONArray adArray = json["ads"].AsArray;
				int i = 0;
				foreach (JSONNode ad in adArray) {
					adList[i] = new WG_GameAd(
						ad["ref"], 
						ad["title"], 
						ad["description"], 
						ad["store_url"],
						ad["web_url"],
						ad["callback_url"],
						ad["image_url"],
						ad["icon_url"]
					);

					i++;
				}

				if (FetchAdsComplete != null) {
					FetchAdsComplete(adList);
				}
			}
		}
	}*/

	public WG_GameAd[] GetAds() {
		if (!this.loaded) {
			return null;
		}

		return this.adList;
	}
}
