Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel
Imports Newtonsoft.Json
Imports VERAG_PROG_ALLGEMEIN.cATEZ_Tariff

Public Class cATEZ_Tariff

    ' Klasse zur Darstellung der Ergebnisse


    Private Shared apiKeyProd = "9a55eba363c2796364ddc1c3b9b126a8"
    Private Shared apiKeyTest = "305f9e546067631848548b461765a3f8"
    Private Shared username = "verag"

    Private Shared baseUrlTest As String = "https://test-tariff.singlewindow.io/api/v2-0/tariff-query/commodity-codes/mappings"
    Private Shared baseUrlProd As String = "https://test-tariff.singlewindow.io/api/v2-0/tariff-query/commodity-codes/mappings"


    Public Class cATEZ_TariffItem_RootItem
        Public Property code As String
        Public Property mappings As List(Of cATEZ_TariffItem_Mapping)
        Public Property [error] As String
    End Class

    Public Class cATEZ_TariffItem_Mapping
        Public Property commodity_code As String
        Public Property description As String
    End Class

    Public Shared Function GetFullTariff_Only1Result(commodityCode As String, fromCountry As String, Optional toCountry As String = "EU", Optional languageCode As String = "DE") As String
        Dim list As New List(Of String)
        list.Add(commodityCode)

        Dim COMM_TARIFF = VERAG_PROG_ALLGEMEIN.cATEZ_Tariff.GetTariffInfo(list, fromCountry, toCountry)

        Dim result = COMM_TARIFF.Find(Function(x) x.code = commodityCode)
        Dim found = False

        If result IsNot Nothing Then
            If result.error <> "" Then
                'Error bei der Abfrage der TNR 
                '  MsgBox(result.error)

            Else
                ''Bei einem Ergebnis -> Treffer

                If result.mappings.Count > 0 Then
                    If result.mappings.Count = 1 Then
                        found = True
                        Return result.mappings(0).commodity_code
                    Else

                        found = True
                        Return "" ' -> problem
                    End If
                End If
            End If
        End If
        Return ""
    End Function

    Public Shared Function GetFullTariff(commodityCode As String, fromCountry As String, Optional toCountry As String = "EU", Optional languageCode As String = "DE") As List(Of String)
        Dim Resultlist As New List(Of String)
        Dim list As New List(Of String)
        list.Add(commodityCode)

        Dim COMM_TARIFF = VERAG_PROG_ALLGEMEIN.cATEZ_Tariff.GetTariffInfo(list, fromCountry, toCountry)

        Dim result = COMM_TARIFF.Find(Function(x) x.code = commodityCode)
        Dim found = False

        If result IsNot Nothing Then
            If result.error <> "" Then
                'Error bei der Abfrage der TNR 
                '  MsgBox(result.error)

            Else
                ''Bei einem Ergebnis -> Treffer

                If result.mappings.Count > 0 Then
                    If result.mappings.Count = 1 Then
                        found = True
                        Resultlist.Add(result.mappings(0).commodity_code)
                    Else
                        For Each item In result.mappings.OfType(Of VERAG_PROG_ALLGEMEIN.cATEZ_Tariff.cATEZ_TariffItem_Mapping)()
                            If item.commodity_code IsNot Nothing AndAlso item.commodity_code <> "" Then
                                Resultlist.Add(item.commodity_code)
                            End If
                        Next

                        found = True
                    End If
                End If
            End If
        End If
        Return Resultlist
    End Function

    Public Shared Function GetTariffInfo(commodities As List(Of String), fromCountry As String, Optional toCountry As String = "EU", Optional languageCode As String = "DE") As List(Of cATEZ_TariffItem_RootItem)
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            ' Create an instance of the HTTP object
            Dim http As New Chilkat.Http()

            ' ==== TIMEOUTS ERHÖHEN ====
            http.ConnectTimeout = 30000   ' 30 Sekunden Verbindungsaufbau
            http.ReadTimeout = 300000      ' 5 min /300 Sekunden Antwort lesen 
            ' =========================

            Dim baseUrl = ""


            If True Then 'VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                ' Set the headers
                http.SetRequestHeader("x-api-key", apiKeyTest)
                http.SetRequestHeader("x-username", username)
                ' Build the base URL
                baseUrl = baseUrlTest
            Else
                ' Set the headers
                http.SetRequestHeader("x-api-key", apiKeyProd)
                http.SetRequestHeader("x-username", username)
                ' Build the base URL
                baseUrl = baseUrlProd
            End If

            ' Manuell den Query-String erstellen
            Dim queryParams As String = "?from=" & fromCountry &
                                    "&to=" & toCountry &
                                    "&language-code=" & languageCode &
                                    "&commodites=" & String.Join(",", commodities)

            ' Kombiniere die Basis-URL mit den Query-Parametern
            Dim url As String = baseUrl & queryParams

            ' Führe die GET-Anfrage aus
            Dim response As String = http.QuickGetStr(url)
            'MsgBox(response.ToString)
            ' Prüfe auf Fehler
            If http.LastMethodSuccess = False Then
                Throw New Exception("HTTP Request failed: " & http.LastErrorText)
            End If


            ' Return the response
            Return ConvertJsonToClass(response.ToString)

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

        End Try
        Return Nothing
    End Function

    Private Shared Function ConvertJsonToClass(response As String) As List(Of cATEZ_TariffItem_RootItem)
        Try
            ' Deserialisiere den JSON-String in eine Liste von RootItem-Objekten
            Dim result As List(Of cATEZ_TariffItem_RootItem) = JsonConvert.DeserializeObject(Of List(Of cATEZ_TariffItem_RootItem))(response)
            Return result
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Throw New Exception("Fehler bei der JSON-Konvertierung: " & ex.Message)
        End Try
    End Function

    'Private Shared Function ProcessApiResponse(jsonResponse As String) As List(Of CommodityMappingData)

    '    Try
    '        Dim result As List(Of RootItem) = JsonConvert.DeserializeObject(Of List(Of RootItem))(response)
    '        Dim response As List(Of RootItem) = GetCommodityMappings(apiKey, username, fromCountry, toCountry, languageCode, commodities)

    '        ' Verarbeite und zeige die Antwort an
    '        For Each item In response
    '            Console.WriteLine("Code: " & item.code)

    '            If item.mappings IsNot Nothing Then
    '                For Each mapping In item.mappings
    '                    Console.WriteLine("  Commodity Code: " & mapping.commodity_code)
    '                    Console.WriteLine("  Description: " & mapping.description)
    '                Next
    '            End If

    '            If Not String.IsNullOrEmpty(item.error) Then
    '                Console.WriteLine("  Error: " & item.error)
    '            End If
    '        Next

    '    Catch ex As Exception
    '        Console.WriteLine("Fehler: " & ex.Message)
    '    End Try





    '    Try
    '        '' Example usage
    '        'Dim apiKey As String = "305f9e546067631848548b461765a3f8"
    '        'Dim username As String = "verag"
    '        'Dim fromCountry As String = "TR"
    '        'Dim toCountry As String = "EU"
    '        'Dim languageCode As String = "DE"
    '        'Dim commodities As New List(Of String) From {
    '        '    "010121000000",
    '        '    "010129100000",
    '        '    "010229290000",
    '        '    "abcd",
    '        '    "efgg",
    '        '    "0123",
    '        '    "123456789012",
    '        '    "3926909790"
    '        '}
    '        Dim items As List(Of Dictionary(Of String, Object)) = JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, Object)))(jsonResponse)

    '        ' Liste für deklarierbare Elemente erstellen
    '        Dim declarableItems As New List(Of CommodityMappingData)()

    '        ' Ergebnisse durchlaufen
    '        For Each item As Dictionary(Of String, Object) In items

    '            Dim tariffItem As New CommodityMappingData() With {
    '                .CommodityCode = item("CommodityCode").ToString(),
    '                .MappedCode = item("MappedCode").ToString(),
    '                .Description = item(item("Description")),
    '                .AdditionalInfo = item("AdditionalInfo").ToString()
    '                }
    '            declarableItems.Add(tariffItem)

    '        Next

    '        Return declarableItems

    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
    '        Console.WriteLine("Error: " & ex.Message)
    '    End Try
    '    Return Nothing
    'End Function
End Class
