using UnityEngine;
using System.Collections;
using SimpleJSON;
using System.Xml;
using System.Text.RegularExpressions;

public class ChatInterface : MonoBehaviour {

	public UIInput yourLanguage; // inspector

	private string[] languages = new string[]{
		"cs", "da", "fi", "hu", "po", "pt", "sv", "tr", "uk", "de"
	};

	private string toLanguage;

	public UIInput input; // inspector

	public ChatOutput output; // inspector

	private string accessToken;

	private string[] dictionary = new string[]{
		"Dung",
		"Cow",
		"Fish",
		"Ser Brakanol"
	};

	public void Start() {
		input.enabled = false;
		StartCoroutine (acquireAccessToken ());
		toLanguage = pick (languages);
	}

	public IEnumerator acquireAccessToken() {
		var url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
		var form = new WWWForm();
		form.AddField( "client_id", "therhinocerosandtheowl" );
		form.AddField( "client_secret", "yLLOxtROGPrdA/Ggu3dDicZnmVoCXUrxxbkpCAWZ3o0=");
		form.AddField( "scope", "http://api.microsofttranslator.com");
		form.AddField( "grant_type", "client_credentials");
		
		var www = new WWW( url, form );
		
		// wait for request to complete
		yield return www;
		
		// and check for errors
		if (www.error == null)
		{
			// request completed!
			JSONNode node = JSON.Parse (www.text);
			accessToken = node["access_token"];
			Debug.Log ("Access token: " + accessToken);
			input.enabled = true;
		} else {
			// something wrong!
			Debug.Log("WWW Error: "+ www.error);
		}
	}

	private string parseTranslationXML(string s) {
		Regex regExp = new Regex(">(.+)<\\/string>");
		Match m = regExp.Match (s);
		return m.Groups [1].Value;
	}

	private IEnumerator translate(string text) {
		string from = yourLanguage.value;
		string to = toLanguage;
		string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + WWW.EscapeURL(text) + "&from=" + from + "&to=" + to + "&contentType=text/plain";
		Debug.Log (uri);
		string authToken = "Bearer" + " " + accessToken;
		var headers = new Hashtable();
		headers.Add("Authorization", authToken);
		WWW www = new WWW (uri, null, headers);
		yield return www;
		string translated = parseTranslationXML(www.text);
		output.onChat(translated);
	}

	private T pick<T>(T[] arr) {
		return arr [Random.Range (0, arr.Length)];
	}

	public void OnSubmit() {
		string text = input.value;
		input.value = "";

		// replace some words
		StartCoroutine (translate (text));
		/*string[] words = text.Split (' ');
		string outText = "";
		for (int i = 0; i < words.Length; ++i) {
			if (i > 0) outText += " ";
			string word = words[i];
			if (word.Length >= 4) {
				words[i] = pick (dictionary);
			}
			outText += words[i];
		}

		output.text = outText;*/

	}
}
