using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class LeaderboardHandlerS : MonoBehaviour {

	public const int MAX_ENTRIES = 6;
	public Text leaderboardText;
	public Text lowerText;
	public InputField inputField;

	private int playerScore;

	void Start() {
		playerScore = TotalScoreS.totalScore;
		TotalScoreS.totalScore = 0;
	}

	void Update () {
		if (Input.GetMouseButtonDown(1)) {
			SceneManager.LoadScene ("MainMenu");
		}
		if (Input.GetKeyDown(KeyCode.Return) && inputField.gameObject.activeSelf) {
			string playerName = inputField.text;
			for (int number = 0; number <= 9; number++) {
				if (playerName.StartsWith("" + number)) {
					inputField.text = "";
					leaderboardText.text = "\n\n\n" + "Your name cannot start with a number";
					inputField.text = "";
					return;
				}
			}
			if (playerName == "CLEAR ALL" || playerName == "clear all") {
				PlayerPrefs.DeleteAll ();
			} else {
				setupLeaderBoard (playerName);
			}
			inputField.gameObject.SetActive (false);
			lowerText.text = "RIGHT CLICK to go back...";
		}
	}

	void setupLeaderBoard(string playerName) {

		int index = 0;
		string currentName;
		bool found = false;
		do {
			currentName = PlayerPrefs.GetString ("" + index++, "NaN");
			if (currentName == playerName) {
				PlayerPrefs.SetInt (playerName, Mathf.Max (playerScore, PlayerPrefs.GetInt (playerName, -1)));
				found = true;
				break;
			}
		} while (currentName != "NaN");
		if (!found) {
			PlayerPrefs.SetString ("" + (index - 1), playerName);
			PlayerPrefs.SetInt (playerName, playerScore);
		}

		List<KeyValuePair<string, int>> entries = new List<KeyValuePair<string, int>> ();
		index = 0;
		do {
			currentName = PlayerPrefs.GetString ("" + index++, "NaN");
			if (currentName != "NaN") {
				int currentScore = PlayerPrefs.GetInt(currentName, -2);
				entries.Add(new KeyValuePair<string, int>(currentName, currentScore));
			}
		} while (currentName != "NaN");

		entries.Sort(MyCompare);

		int entryNumber = 1;
		leaderboardText.text = "";
		foreach (KeyValuePair<string, int> entry in entries) {
			leaderboardText.text += entryNumber + ". " + entry.Key + " (" + entry.Value + ")\n";
			if (++entryNumber > MAX_ENTRIES) {
				break;
			}
		}
	}

	static int MyCompare(KeyValuePair<string, int> a, KeyValuePair<string, int> b) {
		return b.Value.CompareTo(a.Value);
	}

}
