// http://akelpad.sourceforge.net/forum/viewtopic.php?p=12612#12612
// Description(1033): Translates selected text using the Google API
// Description(1049): Перевод текста используя Google-API
// Version: 3.2 (2016.09.10)
// Author: VladSh
// 
// Arguments:
// 	-lngS (<lng> / [auto]) - source language; auto - for autodetect
// 	-lngT (<lng> / [ru])   - target language
// 	-Msg ([0] / 1)         - show the result in MessageBox
// 	-resType values in arguments (does not make sense with Msg=1):
//			0 - selected text is replaced by the translation
//			1 - copy to clipboard
//			2 - display the result in new tab
//			3 - output to Log-plugin console
// 
// Usage:
// 	-"Translate: Auto -> Ru (Google)" Call("Scripts::Main", 1, "TranslateWithGoogleAPI.js", `-lngT="ru" -Msg=1`)		- autodetect source language + display the result in MessageBox
// 	-"Перевести: Ru -> En (Google)" Call("Scripts::Main", 1, "TranslateWithGoogleAPI.js", `-lngS="ru" -lngT="en"`)		- translate ru -> en + source text is replaced by the translation

var langSource = AkelPad.GetArgValue("lngS", "auto");
var langTarget = AkelPad.GetArgValue("lngT", "ru");
var nMsgBox = AkelPad.GetArgValue("Msg", 0);
var nResultType = AkelPad.GetArgValue("resType", 0);

var req = createRequestObject();
if (req) {
	var newline = AkelPad.GetEditNewLine(0);
	var selection = AkelPad.GetSelText(newline);
	if (selection) {
		var resultText;		//в эту переменную возвращается результат в виде текста, иначе undefined
		selection = encodeURIComponent(selection);
		
		var url = "http://translate.google.cn/translate_a/single";
		var params = "client=qlt&dt=bd&dt=t&sl=" + langSource + "&tl=" + langTarget + "&q=" + selection;
		
		try {
			req.open("POST", url, false);
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			req.onreadystatechange = function() {
				if (req.readyState == 4) {   //только при состоянии "complete"
					if (req.status == 200) {  //только для статуса "OK"
						//обработка ответа
						try {
							resultText = req.responseText;
//							WScript.Echo(resultText);
							eval("var resultObject = " + resultText);
							resultText = resultObject[0][0][0];
							resultText = resultText.replace(/&amp;/gm, '&');
							resultText = resultText.replace(/&lt;/gm, '<');
							resultText = resultText.replace(/&gt;/gm, '>');
							resultText = resultText.replace(/&quot;/gm, '"');
						}
						catch (e) {
							showErrorMessage("There is no error output object, possibly changed API format.", true);
						}
					}
					else {
						showErrorMessage("Unable to retrieve data" + (req.statusText ? " (" + req.statusText + ")" : "") + "!", true);
					}
				}
			};
			req.send(params);
		}
		catch(e)
			{ showErrorMessage(e, true); }
		
		if (resultText) {
			var nResultAction;
			
			if (nMsgBox == 1) {
				if (resultText != selection) {
					nResultAction = AkelPad.MessageBox(AkelPad.GetEditWnd(), "Result text:" + "\r\r" + resultText + "\r\r" + "Yes - replace selected (source) text" + "\r" + "No - copy to clipboard", WScript.ScriptName, 32 + 3);
					if (nResultAction == 2) WScript.Quit();
				}
				else {
					AkelPad.MessageBox(AkelPad.GetEditWnd(), "Translation for '" + selection + "' is missing.", WScript.ScriptName, 64);
					WScript.Quit();
				}
			}
			else {
				switch (nResultType) {
					case 2:
						AkelPad.SendMessage(AkelPad.GetMainWnd(), 273 /*WM_COMMAND*/, 4101 /*wParam=MAKEWAPARAM(0,IDM_FILE_NEW)*/, 1 /*lParam=TRUE*/);
						AkelPad.SendMessage(AkelPad.GetMainWnd(), 1230 /*AKD_SETNEWLINE*/, 0, newline);		//выставление такого же формата новой строки, как и в исходном файле
						break;
					case 3:
						AkelPad.Call("Log::Output", 4, resultText, -1, 2);
						WScript.Quit();
				}
			}
			if (nResultAction == 7 || nResultType == 1)
				AkelPad.SetClipboardText(resultText);
			else
				AkelPad.ReplaceSel(resultText, -1);
		}
	}
}

function createRequestObject() {
	if (typeof(XMLHttpRequest) === 'undefined') {
		XMLHttpRequest = function() {
			try { return new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(e) {
				try { return new ActiveXObject("Microsoft.XMLHTTP"); }
				catch(e) {
					throw new Error("Your system does not support XMLHttpRequest.");
				}
			}
		};
	}
	return new XMLHttpRequest();
}

function showErrorMessage(pText, bQuit) {
	AkelPad.MessageBox(AkelPad.GetEditWnd(), pText, WScript.ScriptName, 16);
	if (bQuit) WScript.Quit();
}