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

public class Highscore : MonoBehaviour {
	InputField inputField;
	Text results;

	// Use this for initialization
	void Start () {
		Canvas canvas = gameObject.GetComponent<Canvas>();
		inputField = canvas.GetComponentInChildren<InputField>();
		Text[] text = canvas.GetComponentsInChildren<Text>();
		results = text[0];
		Text playerScore = text[1];

		GameObject scoreHolder = GameObject.Find ("ScoreHolder");
		if (scoreHolder == null) {
			playerScore.text = "";
			inputField.enabled = false;
			DownloadHighScore ();
		} else {
			int score = scoreHolder.GetComponent<ScoreHolder>().getScore();
			Debug.Log (String.Format ("Score: {0}", score));
			playerScore.text = String.Format ("You scored: {0}", score);
			inputField.ActivateInputField();
			inputField.onEndEdit.AddListener (delegate {ValueChanged (score);});
			Destroy (scoreHolder);
		}
	}

	void ValueChanged (int score) {
		if (inputField.text != "") {
			inputField.enabled = false;
			SubmitHighscore(inputField.text, score);
		} else {
			inputField.ActivateInputField();
		}
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	string url = "http://dreamlo.com/lb/";
	string privateCode = "irtealppTEGOaXJ7vxq2bAbzChoWwRbE-iJ4j8k6GMFQ";

	public void SubmitHighscore(string player, int score) {
		StartCoroutine(SubmitHighscoreEnumerator(player, score));
	}
	
	IEnumerator SubmitHighscoreEnumerator(string player, int score) {
		WWW www = new WWW(url + privateCode + "/add-pipe/" + player + "/" + score);
		yield return www;
		
		if (www.error != null) {
			results.text = "Submit failed: " + www.error;
		} else if (www.text.StartsWith ("ERROR:")) {
			results.text = "Submit failed: " + www.text;
		} else {
			results.text = PrintHighscore (www.text);
		}
	}

	public void DownloadHighScore() {
		StartCoroutine (DownloadHighscoreEnumerator ());
	}

	IEnumerator DownloadHighscoreEnumerator() {
		WWW www = new WWW(url + privateCode + "/pipe/");
		yield return www;
		
		if (www.error != null) {
			results.text = "Download failed: " + www.error;
		} else if (www.text.StartsWith ("ERROR:")) {
			results.text = "Download failed: " + www.text;
		} else {
			results.text = PrintHighscore (www.text);
		}
	}
	
	String PrintHighscore(string rawText) {
		Debug.Log (rawText);
		string[] lines = rawText.Split(new char[] {'\n'}, System.StringSplitOptions.RemoveEmptyEntries);
		string text = "";
		foreach (string line in lines) {
			string[] columns = line.Split(new char[] {'|'});
			string player = columns[0];
			string score = columns[1];
			text += player + "\t" + score + "\n";
		}
		return text;
	}
	
}