Imports System.Web
Imports System.Web.Routing
Imports iTextSharp.text.xml.simpleparser

Public Class cDeeplAPI

    'PROD
    Shared API_STRING As String = "https://api-free.deepl.com"
    Shared AUTH_KEY As String = "57bad342-00e2-6732-da08-b6733fb09a91:fx"


    Shared Function deepl_Translate(textTotranslate As String, ByRef textResult As String, targetLAN As String, Optional sourceLAN As String = "DE") As Boolean
        textResult = textTotranslate
        Dim rest As New Chilkat.Rest

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        '  Connect to the REST server.
        Dim bTls As Boolean = True
        Dim port As Integer = 443
        Dim bAutoReconnect As Boolean = True
        Dim success As Boolean = rest.Connect(API_STRING, port, bTls, bAutoReconnect)

        If (success <> True) Then
            Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
            Debug.WriteLine(rest.LastErrorText)
            Return False
        End If

        '---------------------------------------------------
        'See the Online Tool for Generating JSON Creation Code
        Dim json As New Chilkat.JsonObject
        ' If sourceLAN <> "" Then json.UpdateNumber("source_lang", sourceLAN)
        json.UpdateString("target_lang", targetLAN)
        json.UpdateString("text", textTotranslate)
        'json.UpdateString("preserve_formatting", 1)
        json.UpdateString("auth_key", AUTH_KEY)

        rest.AddHeader("Accept", "application/json")
        rest.AddHeader("Content-Type", "application/x-www-form-urlencoded")
        '        client.DefaultRequestHeaders.Accept.Add(New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        'client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");  

        'rest.AddHeader("Authorization", AUTH_KEY)
        ' rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")
        'rest.AddHeader("Accept", "*/*")
        'rest.AddHeader("User-Agent", "PostmanRuntime/7.29.0")
        'rest.AddHeader("Connection", "keep-alive")
        'rest.AddHeader("Accept-Encoding", "gzip, deflate, br")
        'rest.AddHeader("Cache-Control", "no-cache")
        'rest.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0")
        ' rest.AddHeader("Content-Type", "application/x-www-form-urlencoded")

        'rest.AddHeader("Accept", "*/*")


        Dim sbRequestBody As New Chilkat.StringBuilder
        'json.EmitSb(sbRequestBody)
        'MsgBox(sbRequestBody.ToString)


        '---------------------------------------------------
        'Dim json As New Chilkat.JsonObject
        'Dim successJsonLoad As Boolean = json.Load("  
        '            {""source_lang"":DE,""target_lang"":""DE"",""text"":""Hello World"",""preserve_formatting"":""1"",""auth_key"":""57bad342-00e2-6732-da08-b6733fb09a91:fx""} ")
        'If (successJsonLoad <> True) Then
        '    MsgBox(json.LastErrorText)
        '    Return False
        'End If
        'Dim sbRequestBody As New Chilkat.StringBuilder
        'json.EmitSb(sbRequestBody)

        '  MsgBox("/v2/translate?auth_key=" & AUTH_KEY & "&target_lang=" & targetLAN & "&text=" & HttpUtility.UrlEncode(textTotranslate) & "")
        Dim sbResponseBody As New Chilkat.StringBuilder
        Dim srch = If(sourceLAN <> "", "&source_lang=" & sourceLAN, "")
        success = rest.FullRequestSb("POST", "/v2/translate?auth_key=" & AUTH_KEY & "&target_lang=" & targetLAN & "&text=" & HttpUtility.UrlEncode(textTotranslate) & srch, sbRequestBody, sbResponseBody)
        '  success = rest.FullRequestSb("POST", "/v2/translate", sbRequestBody, sbResponseBody)

        ' MsgBox(success)

        If (rest.LastMethodSuccess <> True) Then
            Console.WriteLine(rest.LastErrorText)
            Return False
        End If

        If success Then
            Dim respStatusCode As Integer = rest.ResponseStatusCode
            'MsgBox(respStatusCode)
            If (respStatusCode = 200) Then
                Try
                    Dim jsonResp = New Chilkat.JsonObject()
                    jsonResp.LoadSb(sbResponseBody)
                    If jsonResp.SizeOfArray("translations") > 0 Then
                        textResult = jsonResp.StringOf("translations[0].text")
                        ' MsgBox("::::::::: " & jsonResp.StringOf("translations[0].text"))
                        Return True
                    End If
                Catch ex As Exception
                    MsgBox(ex.Message & ex.StackTrace)
                End Try
            End If

        End If

        Return False
    End Function


End Class
