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

public class WG_Leaderboard : MonoBehaviour {

	public delegate void LeaderboardHandler(WG_LeaderboardStat[] stats);
	public static event LeaderboardHandler LeaderboardRecordComplete;

	public string leaderboardKey = "KEY";
	public bool test = false;

	private WG_LeaderboardStat[] statList;

	public static WG_Leaderboard instance;

	void Awake() {
		if (WG_Leaderboard.instance == null) {
			WG_Leaderboard.instance = this;
			DontDestroyOnLoad(this.gameObject);
		}
		else if (WG_Leaderboard.instance != this) {
			Destroy(this.gameObject);
		}
	}

	public void RecordScore(int score) {
		string url = "https://wirthwhilegaming.com/api/leaderboard/record_score?leaderboard_key="+this.leaderboardKey+"&score="+score;
		if (this.test) {
			url = url + "&test=1";
		}

		StartCoroutine(SubmitScore(url));
	}

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

			if (webRequest.isNetworkError)
			{
				Debug.Log("Web request error: " + webRequest.error);
			}
			else
			{
				JSONNode json = JSON.Parse(webRequest.downloadHandler.text);
				if (json["success"] != null && json["success"] != false && json["scores"] != null)
				{
					this.statList = new WG_LeaderboardStat[json["scores"].Count];
					JSONArray statArray = json["scores"].AsArray;
					int i = 0;
					foreach (JSONNode stat in statArray)
					{
						statList[i] = new WG_LeaderboardStat(
							stat["timeframe"],
							int.Parse(stat["score_max"]),
							int.Parse(stat["score_min"]),
							int.Parse(stat["score_count"]),
							int.Parse(stat["score_average"]),
							int.Parse(stat["score_best"]),
							int.Parse(stat["percentile"])
						);

						i++;
					}

					if (LeaderboardRecordComplete != null)
					{
						LeaderboardRecordComplete(statList);
					}
				}
			}
		}
	}
}
