#Include Once "../Inc/Translate.bi"

Dim Shared Enc As EncodeUTFHTML

Function ClassTranslate.Translate(boolParam As BOOL) As BOOL

	Dim As String sText, sLanguage, sURL

	Dim As HINTERNET hInternet,hURL

	Dim As String*1024 cBuffer

	Dim As Integer dwBytesRead

	If boolParam = TRUE Then
		
		Sleep(200)

		keybd_event(VK_CONTROL, 0,0,0)

		keybd_event(67, 0,0,0)

		Sleep(50)

		keybd_event(VK_CONTROL, 0,KEYEVENTF_KEYUP,0)

		keybd_event(67,0,KEYEVENTF_KEYUP,0)
		
		sText = GetClipBoardText()

      If sText[Len(sText)-1] = 0 And sText[Len(sText)] = 0 Then      	
      	sText = Mid(sText,1,Len(sText)-1)
      EndIf
      
		SetGadgetText( EDITOR_IN , sText)
		
		HideWindow(hwndMain, FALSE)

	Else

		sText = GetGadgetText( EDITOR_IN )

	EndIf

	If GetItemComboBox(COMBO_LANG)=1 Then

		sText = Enc.GetUtfHtmlSimvols(sText)

		sLanguage = "en"

	Else
		
		sText = ReplaceString(sText,Chr(10),"%0A",,1)
		
		sText = ReplaceString(sText,"&","%26",,1)
		
		sText = ReplaceString(sText,"#","%23",,1)

		sLanguage = "ru"

	EndIf

	sURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20140117T115509Z.4b400182986ee79a.b6f637125fa5ce64c975ecd6b3c2c97f03d09480&text=" & sText & "&lang=" & sLanguage

	hInternet = InternetOpen(_
					"Microsoft Internet Explorer",_
					INTERNET_OPEN_TYPE_PRECONFIG,_
					NULL, NULL, 0)

	If hInternet <> FALSE Then

		hURL = InternetOpenUrl(_
						hInternet,_
						sURL,_
						NULL, 0, 0, 0)

		If hURL <> FALSE Then

            sText=""
        
				Do
 
					Var bResult = InternetReadFile(_
												hURL,_
												@cBuffer,_
												1024,_
												@dwBytesRead)

					For i As Integer = 0 To dwBytesRead-1
						sText &= Hex(cBuffer[i])
					Next
					
				Loop Until dwBytesRead = 0			

				SetGadgetText(EDITOR_OUT, Enc.GetSimvols(sText))				

				Function = TRUE

			InternetCloseHandle(hURL)

		EndIf

		InternetCloseHandle(hInternet)

	EndIf

End Function
