Imports System.Net
Imports Chilkat
Imports iTextSharp.text.pdf.codec.wmf
Imports Newtonsoft.Json.Linq
Imports VERAG_PROG_ALLGEMEIN.cCreditSafeAPI

Public Class cNorsware


    'PROD
    Shared API_STRING As String = "http://54.93.249.123"
    Shared token As String = ""
    Public dataTable As New DataTable()




    Shared Function SendRequestAuthentificationToken(ByVal myuri As String, ByVal contentType As String, ByVal method As String, ByRef Itoken As String) As String
        Try
            If Itoken <> "" Then Return "token filled"

            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            Dim rest As New Chilkat.Rest
            Dim success As Boolean


            Dim bTls As Boolean = False
            Dim port As Integer = 7128
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText

            End If


            Dim json As New Chilkat.JsonObject
            'json.UpdateString("username", user)
            'json.UpdateString("password", pw)

            rest.AddHeader("Content-Type", contentType)

            Dim sbRequestBody As New Chilkat.StringBuilder
            json.EmitSb(sbRequestBody)


            Dim sbResponseBody As New Chilkat.StringBuilder
            Dim ResponseStr = rest.FullRequestSb(method, myuri, sbRequestBody, sbResponseBody)


            If (rest.ResponseStatusCode <> 200) Then
                Return rest.ResponseStatusCode & " " & rest.ResponseStatusText
            End If

            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.LoadSb(sbResponseBody)

            token = jsonResp.StringOf("token")
            Itoken = token

            Return rest.ResponseStatusCode & " " & rest.ResponseStatusText
        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function



    Shared Function UploadPDFWithAuthHeader(pdfStringSource As String, acceptContentType As String, method As String, authenticationToken As String, ByRef dataTable As DataTable) As String
        Try

            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = False
            Dim port As Integer = 7135
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
            End If


            Dim fileStream As New Chilkat.Stream
            fileStream.SourceFile = pdfStringSource

            rest.AddHeader("Authorization", "Bearer " & authenticationToken)
            rest.AddHeader("Content-Type", "multipart/form-data")

            rest.PartSelector = "1"
            rest.AddHeader("Content-Type", "pdf")
            rest.AddHeader("Content-Disposition", "form-data; name=""file""; filename=""starfish.pdf""")
            rest.SetMultipartBodyStream(fileStream)
            rest.PartSelector = "0"


            Dim responseBody As String = rest.FullRequestMultipart(method, API_STRING & ":7135/api/File/UploadFile")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> 200) Then
                Return rest.ResponseStatusCode & " " & rest.ResponseStatusText
            End If


            Debug.WriteLine("File uploaded")


            Dim jsonArray As New Chilkat.JsonArray
            Dim success2 As Boolean = jsonArray.Load(responseBody)
            If (success2 <> True) Then
                Debug.WriteLine(jsonArray.LastErrorText)
                Return "Verbindungsfehler"
            End If


            Dim num As Integer = jsonArray.Size
            If num = -1 Then
                Return "Fehler"
            End If


            Dim j As Integer = 0
            While j < num

                Dim pdfSite As Chilkat.JsonObject = jsonArray.ObjectAt(j)

                Dim R As DataRow = dataTable.NewRow
                R("adi") = pdfSite.StringOf("adi")
                R("id") = pdfSite.StringOf("id")
                R("ihracatBeyannamesi") = IIf(j = 0, True, False)
                R("ekBelge") = IIf(j = 0, False, True)
                R("sira") = j + 1
                R("secildi") = pdfSite.BoolOf("secildi")
                R("ogretildi") = pdfSite.IntOf("ogretildi")
                R("kayitTarihi") = pdfSite.StringOf("kayitTarihi")
                R("dosyaGrupId") = pdfSite.StringOf("dosyaGrupId")
                dataTable.Rows.Add(R)

                j = j + 1
            End While


            Return "File uploaded (Anzahl Seiten " & num & ")"

        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function


    Shared Function authenticate(username As String, passwort As String, ByRef token As String) As String

        Dim myUri As String = API_STRING & ":7128/api/Kullanici/Giris/" & username & "/" & passwort
        Dim response = SendRequestAuthentificationToken(myUri, "application/json", "GET", token)

        Return response


    End Function



    Shared Function sendSelection(authenticationToken As String, acceptContentType As String, ByRef dataTable As DataTable, ByRef groupID As String) As String

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        Dim rest As New Chilkat.Rest
        Dim success As Boolean

        'Dim jsonreqbody As New Chilkat.JsonObject
        'success = jsonreqbody.AddArrayAt(-1, "")
        Dim JArray As New Chilkat.JsonArray
        'JArray = jsonReqBody.ArrayAt(jsonReqBody.Size - 1)
        Dim json As Chilkat.JsonObject
        Dim j As Integer = 0
        For Each row In dataTable.Rows

            JArray.AddObjectAt(j)
            json = JArray.ObjectAt(j)

            json.UpdateString("adi", row("adi"))
            json.UpdateString("dosyaGrupId", row("dosyaGrupId"))
            json.UpdateBool("ihracatBeyannamesi", row("ihracatBeyannamesi"))
            json.UpdateBool("ekBelge", row("ekBelge"))
            json.UpdateNumber("sira", row("sira"))
            json.UpdateNumber("ogretildi", row("ogretildi"))
            json.UpdateBool("secildi", row("secildi"))
            json.UpdateString("id", row("id"))
            json.UpdateString("kayitTarihi", row("kayitTarihi"))
            JArray.EmitCompact = False
            Debug.WriteLine(JArray.Emit())

            j = j + 1
        Next


        Dim bTls As Boolean = False
        Dim port As Integer = 7135
        Dim bAutoReconnect As Boolean = True
        success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
        If (success <> True) Then
            Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
            Debug.WriteLine(rest.LastErrorText)
        End If

        Dim myUrl As String = API_STRING & ":7135/api/MachineLearning/Learn"
        rest.AddHeader("Content-Type", "application/json")
        rest.AddHeader("Authorization", "Bearer " & authenticationToken)
        rest.AddHeader("Accept", acceptContentType)

        'Debug.WriteLine(JArray.Emit())
        'Return jsonReqBody.ToString

        Dim jsonResponseStr As String = rest.FullRequestString("POST", myUrl, JArray.Emit())
        If (rest.LastMethodSuccess <> True) Then
            Debug.WriteLine(rest.LastErrorText)
            Return rest.LastErrorText
        End If


        Dim result = New Chilkat.JsonObject()
        success = result.Load(jsonResponseStr)

        groupID = result.StringOf("dosyaGrupId")

        Return success

    End Function


    Shared Function getData(authenticationToken As String, acceptContentType As String, ByRef groupID As String, ByRef doc As digitDocumnent) As String

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        Dim rest As New Chilkat.Rest
        Dim success As Boolean




        Dim bTls As Boolean = False
        Dim port As Integer = 7128
        Dim bAutoReconnect As Boolean = True
        success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
        If (success <> True) Then
            Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
            Debug.WriteLine(rest.LastErrorText)
        End If

        Dim myUrl As String = API_STRING & ":7128/api/MachineLearning/VeriGetir/" & groupID
        rest.AddHeader("Content-Type", "application/json")
        rest.AddHeader("Authorization", "Bearer " & authenticationToken)
        rest.AddHeader("Accept", acceptContentType)

        'Debug.WriteLine(JArray.Emit())
        'Return jsonReqBody.ToString

        Dim jsonResponseStr As String = rest.FullRequestNoBody("GET", myUrl)
        If (rest.LastMethodSuccess <> True) Then
            Debug.WriteLine(rest.LastErrorText)
            Return rest.LastErrorText
        End If

        'Dim doc = New digitDocumnent()
        Dim json As New Chilkat.JsonObject
        success = json.Load(jsonResponseStr)
        If (success <> True) Then
            Debug.WriteLine(json.LastErrorText)
            Return "Verbindungsfehler"
        End If



        doc.abs = json.StringOf("gondericiUnvan")
        doc.absNr = json.StringOf("gondericiVergiNo")
        doc.absAdresse = json.StringOf("gondericiAdres")
        doc.absStadt = json.StringOf("gondericiSehirUlke")

        doc.empf = json.StringOf("aliciUnvan")
        'doc.empfNr = json.StringOf("gondericiVergiNo")
        doc.empfAdresse = json.StringOf("aliciAdres")
        doc.empfStadt = json.StringOf("aliciSehirUlke")

        doc.MRN = json.StringOf("ihracatBeyanNumarasi")
        doc.pos = json.StringOf("kalemSayisi")
        doc.pkgSum = json.StringOf("toplamKapAdet")
        doc.mass = json.StringOf("toplamBrut")
        doc.totalAmount = json.StringOf("toplamFaturaBedeli")


        Dim positions As Chilkat.JsonArray = json.ArrayOf("entityIslenmisVeriEk")
        If (json.LastMethodSuccess = False) Then
            Return "positions not found."
        End If

        Dim numPositions As Integer = positions.Size

        Dim j As Integer = 0
        While j < numPositions

            Dim posObj As Chilkat.JsonObject = positions.ObjectAt(j)

            Dim R As DataRow = doc.positonTable.NewRow
            R("esyaTanim") = posObj.StringOf("esyaTanim")
            R("gtip") = posObj.StringOf("gtip")
            R("kapAdet") = posObj.IntOf("kapAdet")
            R("kalemFiyati") = posObj.StringOf("kalemFiyati")
            R("brut") = posObj.IntOf("brut")
            R("net") = posObj.StringOf("net")
            R("parcalimi") = posObj.BoolOf("parcalimi")
            R("id") = posObj.StringOf("id")
            R("kayitTarihi") = posObj.StringOf("kayitTarihi")

            doc.positonTable.Rows.Add(R)

            j = j + 1


        End While

        Return jsonResponseStr

    End Function





End Class

Public Class digitDocumnent

    Public Property abs As String
    Public Property absNr As String
    Public Property absAdresse As String
    Public Property absStadt As String
    Public Property empf As String
    Public Property empfNr As String
    Public Property empfAdresse As String
    Public Property empfStadt As String
    Public Property MRN As String
    Public Property pos As Integer
    Public Property pkgSum As Integer
    Public Property mass As Double
    Public Property totalAmount As String
    Public Property positonTable As DataTable


    Public Sub New(dt As DataTable)
        positonTable = dt
    End Sub
End Class


