using Assets.Scripts.API;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
using System.Collections;

public class HighScores : MonoBehaviour {

	public Text ScoreText;
	public Server Server;
	public Score[] highscores;

	private bool updatedScores = false; //TODO: Not very elegant, can we instead load scores sync in Start?

	// Use this for initialization
	void Start () {
		ScoreText.text = "";
		Server = gameObject.GetComponent(typeof(Server)) as Server;
	}

	// Update is called once per frame
	void Update () {
		if (!updatedScores) {
			if (Server.Scores.status.Equals("ok")) {
				Score[] highScores = Server.Scores.scores;
				Array.Sort(highScores, delegate(Score x, Score y) {return y.score.CompareTo(x.score);});

				Debug.Log(String.Format("We got {0} scores.", highScores.Length));
				if (Server.Scores.scores.Length > 0) {

					for (int i = 0; i < highScores.Length; i++) {
						Score score = highScores [i];
						string name = score.playerName;
						if (score.team != null && score.team.Length > 0) {
							name += " (" + score.team + ")";
						}
						ScoreText.text += WWW.UnEscapeURL(name) + ": " + score.score + " points\n";
					}
				} else {
					ScoreText.text = "No high-score yet... Play a game and show you are the best!";
				}
				updatedScores = true;
			}
		}
	}

	public void OnButtonBackClicked()
	{
		SceneManager.LoadScene("Menu");
	}
}
	