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

public class LeaderboardManager : MonoBehaviour
{
	public string request = "http://corder.tech/mocha/users/*";
	public Text Usernames;
	public Text Scores;

	private List<PlayerInfo> players;
	private int currentPage;

	void Start()
	{
		CallGetData();
	}

	public void CallGetData()
	{
		DisplayAllSeparated(request, Usernames, Scores);
	}

	public void DisplayAllSeparated(string request, Text Usernames, Text Scores)
	{
		MochaParser parser = new MochaParser ();

		StartCoroutine (parser.GrabLeaderboard(request, Usernames, Scores, this));
	}

	public void setPlayers(List<PlayerInfo> p)
	{
		players = p;
	}

	public void setInitialBoard(Text u, Text s)
	{
		currentPage = 1;
		Usernames = u;
		Scores = s;

		string usernameOutput = "Username";
		string scoreOutput = "Score";

		/* 
		 * Just an extra step in case for whatever reason
		 * the leaderboard length is less than 10.
		 * */

		int boardlength = players.Count;

		if (boardlength > 10)
			boardlength = 10;

		for(int i = 0; i < boardlength; ++i)
		{
			usernameOutput += "\n" + players[i].username;
			scoreOutput += "\n" + players [i].score;
		}

		Usernames.text = usernameOutput;
		Scores.text = scoreOutput;
	}

	public void nextPage()
	{
		int currentIndex = currentPage * 10;
		int test = players.Count - currentIndex;

		if (test <= 0)
		{
			return;
		}

		else
		{
			string usernameOutput = "Username";
			string scoreOutput = "Score";
			int pagelength = 10;

			if (test < pagelength) 
			{
				pagelength = test;
			}

			for (int i = currentIndex; i < (currentIndex + pagelength); ++i)
			{
				usernameOutput += "\n" + players[i].username;
				scoreOutput += "\n" + players [i].score;
			}

			Usernames.text = usernameOutput;
			Scores.text = scoreOutput;
			currentPage += 1;
		}
	}

	public void previousPage()
	{
		if (currentPage <= 1)
		{
			return;
		}

		else
		{
			currentPage -= 1;
			int currentIndex = currentPage * 10;
			string usernameOutput = "Username";
			string scoreOutput = "Score";
			int pagelength = 10;

			for (int i = (currentIndex - pagelength); i < currentIndex; ++i) {
				usernameOutput += "\n" + players [i].username;
				scoreOutput += "\n" + players [i].score;
			}

			Usernames.text = usernameOutput;
			Scores.text = scoreOutput;
		}
	}
}
