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

public class SendHighScore : MonoBehaviour
	{
	public Text playerName;
	public Text score;

	public GameObject pannel_1;
	public GameObject pannel_2;
	public GameObject pannel_3;

	public Text score_rank;
	public Text score_value;
	public Text score_name;

	public Text text_error;
	public GameObject button_error;

	public void activateAndSetScore( int s )
		{
		pannel_1.SetActive(true);
		score.text = s.ToString();
		}

	public void click_close()
		{
		pannel_2.SetActive(false);
		pannel_3.SetActive(false);

		Application.LoadLevel ("splash");
		}

	public void click_submit()
		{
        if (playerName.text.Length >= 3)
        	submit(playerName.text, int.Parse(score.text));
		}

    public void submit(string n, int s)
		{
        Debug.Log("submit " + n + " : " + s);
		pannel_1.SetActive(false);
		pannel_2.SetActive(true);
		text_error.text = "Loading...";
		button_error.SetActive( false );
		StartCoroutine(loadRank(n,s));
		}

	IEnumerator loadRank( string n , int s )
		{
		string url = "http://buildanddefend.com/other/GGJ15/?name=" + n + "&score=" + s;
		WWW www = new WWW (url);

		yield return www;

		if (www.error != null)
			{
			Debug.Log("Impossible to see the highscores\n" + www.error);
			text_error.text = "Impossible to see the highscores\n" + www.error;
			button_error.SetActive(true);
			}
		else
			{
			string r = www.text;
			string[] rs = r.Split('\n');

			string t_rank = "";
			string t_name = "";
			string t_score = "";

			foreach( string e in rs )
				{
				string[] rs2 = e.Split('\t');
				if(rs2.Length!=3)
					break;
				t_rank += rs2[0] + "\n";
				t_score += rs2[1] + "\n";
				t_name += rs2[2] + "\n";
				}

			score_rank.text = t_rank;
			score_value.text = t_score;
			score_name.text = t_name;

			showRanks();
			}
		}

	public void showRanks()
		{
		pannel_2.SetActive(false);
		pannel_3.SetActive(true);
		}

	}
