using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class HSController : MonoBehaviour
{
	private static HSController _instance;
	public static HSController shared { get{ return _instance; } }
	
//    private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
	private string secretKey="funtime";
	
	private string addScoreURL = "http://www.wonthelp.info/spellbox/sendScore.php"; //be sure to add a ? to your url
    private string highscoreURL = "http://www.wonthelp.info/spellbox/getScores.php";

	public GUIStyle nameFieldStyle;
	public GUIStyle submitButtonStyle;
	
	public LetterBoard ScoreDelegate;
	
//	public string addScoreURL = "sendScore.php?"; //be sure to add a ? to your url
//    public string highscoreURL = "getScores.php";
 
	TextMesh _area;
	
	void Awake()
	{
		_instance = this;	
		_area = GameObject.Find("Highscores").GetComponent<TextMesh>();
	}
	
    void Start()
    {
//        StartCoroutine(GetScoresCoroutine());
    }
 
	public void PostScore(string name, int score)
	{
		StartCoroutine(PostScoreCoroutine(name, score));	
	}
	
	public void GetScores()
	{
		StartCoroutine("GetScoresCoroutine");
	}
	
	public void SetTextBottom(bool bottom)
	{
		if(bottom)
		{
			transform.position = new Vector3(0.5f, 0.48f, 0.0f);	
		}
		else
		{
			transform.position = new Vector3(0.5f, 0.84f, 0.0f);	
		}
	}
	
    // remember to use StartCoroutine when calling this function!
    IEnumerator PostScoreCoroutine(string name, int score)
    {
		name = name.Replace(" ", string.Empty);
		
        //This connects to a server side php script that will add the name and score to a MySQL DB.
        // Supply it with a string representing the players name and the players score.
        string hash = Utils.Md5Sum(name + score + secretKey);
//        string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
//		WWW hs_post = new WWW(post_url);
//		string post_url = "sendRequest=coineater" + "&name=" + WWW.EscapeURL(name) + "&score=" + score;
 
        // Post the URL to the site and create a download object to get the result.
		WWWForm form = new WWWForm();
		form.AddField("table", "scores");
		form.AddField("name", WWW.EscapeURL(name));
		form.AddField("score", score);
		form.AddField("hash", hash);
	    WWW hs_post = new WWW(addScoreURL, form);
		
        yield return hs_post; // Wait until the download is done
 
		Debug.Log("hs_post: " + hs_post.text);
		
        if (hs_post.error != null)
        {
//            print("There was an error posting the high score: " + hs_post.error);
			Debug.Log("There was an error getting the high score: " + hs_post.error);
        }
		
		ScoreDelegate.DonePostingScore();
    }
 
    // Get the scores from the MySQL DB to display in a GUIText.
    // remember to use StartCoroutine when calling this function!
    IEnumerator GetScoresCoroutine()
    {
//        gameObject.guiText.text = "LOADING SCORES";
		
//		WWW hs_get = new WWW(highscoreURL);
		
		WWWForm form = new WWWForm();
		form.AddField("table", "scores");
	    WWW hs_get = new WWW(highscoreURL, form);
        yield return hs_get;
 
        if (hs_get.error != null)
        {
            Debug.Log("There was an error getting the high score: " + hs_get.error);
        }
        else
        {
			_area.text = hs_get.text;
//            gameObject.guiText.text = "HIGH SCORES:\n\n" + hs_get.text; // this is a GUIText that will display the scores in game.
        }
		
		
		Debug.Log("scores: " + hs_get.text);
		
		//if(ScoreDelegate)
		//	ScoreDelegate.SetScores(ParseScores(hs_get.text));
    }
	
	List<KeyValuePair<string, uint>> ParseScores(string scoreText)
	{
		List<KeyValuePair<string, uint>> namesAndScores = new List<KeyValuePair<string, uint>>();
		
		string[] lines = scoreText.Split(new string[] { "\n" }, System.StringSplitOptions.RemoveEmptyEntries);
		
		foreach(string line in lines)
		{
//			string[] separators = {",", ".", "!", "?", ";", ":", " "};
			string[] lineSplit = line.Split(new string[] { "---" }, System.StringSplitOptions.None);
            string name = lineSplit[0].Trim();
			string scoreString = lineSplit[1].Trim();
			uint score = System.Convert.ToUInt32(scoreString);
			namesAndScores.Add(new KeyValuePair<string, uint>(name, score));
			
			Debug.Log("name: " + name + " score: " + score);
		}
		
		return namesAndScores;
	}
	
	public void HideScores()
	{
		StopCoroutine("GetScoresCoroutine");
		gameObject.guiText.text = "";
	}
}