using Assets.Scripts.API;
using Assets.Scripts.Utils;
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 () {
		BackButtonHelper.playOnBack();
		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++) {
						int position = i + 1;
						string positionText = position + (position == 1 ? "st" :
							position == 2 ? "nd" :
							position == 3 ? "rd" : "th");
						Score score = highScores [i];
						string name = score.playerName;
						if (score.team != null && score.team.Length > 0) {
							name += " (" + score.team + ")";
						}
						string entryText = positionText + " " + WWW.UnEscapeURL (name) + ": " + score.score + " points\n";
						if (position <= 3)
							entryText = "<b><size=30>" + entryText + "</size></b>";
						else if (position == 4)
							entryText = "\n" + entryText;
						ScoreText.text += entryText;
					}
				} else {
					ScoreText.text = "No high-score yet... Play a game and show you are the best!";
				}
				updatedScores = true;
			}
		}
	}

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