Imports System.Net.Http
Imports System.Web
Imports System
Imports Microsoft.AspNetCore.Authentication.Cookies
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Hosting
Imports Microsoft.AspNetCore.Http
Imports Microsoft.Extensions.Configuration
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Hosting
Imports System.Collections.Specialized
Imports System.Text
Imports System.IO
Imports VERAG_PROG_ALLGEMEIN
Imports System.Windows.Forms
Imports System.Drawing


Public Class cHMRC

    'TEST
    'Shared API_STRING As String = "https://test-api.service.hmrc.gov.uk"
    'Shared CLIENT_ID As String = "xybTOMaQWcuifeW5xnGggojlACWC"
    'Shared CLIENT_SECRET As String = "bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1"

    'PROD
    Shared API_STRING As String = "https://api.service.hmrc.gov.uk"
    Shared CLIENT_ID As String = "qO1kqyMtFnvHi9XpRVJBGTCrNpno"
    Shared CLIENT_SECRET As String = "3169852a-afa5-4adb-837c-fbd4d0cd4c7e"


    Public Class cHMRCCredentials
        Public CLIENT_ID As String = ""
        Public CLIENT_SECRET As String = ""
        Public API_STRING As String = ""
    End Class

    Shared Function getCredentials(HMRC_APPLICATION) As cHMRCCredentials
        Dim cHMRCCredentials = New cHMRCCredentials
        Select Case HMRC_APPLICATION
            Case "AVISO"
                If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                    cHMRCCredentials.API_STRING = "https://test-api.service.hmrc.gov.uk"
                    cHMRCCredentials.CLIENT_ID = "xybTOMaQWcuifeW5xnGggojlACWC"
                    cHMRCCredentials.CLIENT_SECRET = "bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1"
                Else
                    cHMRCCredentials.API_STRING = "https://api.service.hmrc.gov.uk"
                    cHMRCCredentials.CLIENT_ID = "qO1kqyMtFnvHi9XpRVJBGTCrNpno"
                    cHMRCCredentials.CLIENT_SECRET = "3169852a-afa5-4adb-837c-fbd4d0cd4c7e"
                End If
            Case "AVISO_ENS"

                If cHMRC_ENS.TEST Or VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                    cHMRCCredentials.API_STRING = "https://test-api.service.hmrc.gov.uk"
                    cHMRCCredentials.CLIENT_ID = cHMRC_ENS.Client_ID
                    cHMRCCredentials.CLIENT_SECRET = cHMRC_ENS.Client_Secret

                Else
                    cHMRCCredentials.API_STRING = "https://api.service.hmrc.gov.uk"
                    cHMRCCredentials.CLIENT_ID = cHMRC_ENS.Client_ID
                    cHMRCCredentials.CLIENT_SECRET = cHMRC_ENS.Client_Secret
                End If
        End Select
        Return cHMRCCredentials
    End Function

    Shared Function SEND_GVMS(GVMS As VERAG_PROG_ALLGEMEIN.cGVMS, Optional updateGMR As String = "")

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then

            '    Dim AccessToken = ""
            'grantAccess(AccessToken, "write:goods-movement-system+read:pull-notifications", "AVISO")

            If TOKEN.token_BEARER_TOKEN <> "" Then
                Dim Notification_Box_Id = ""
                Dim Notification_Message_Id = ""
                If genGVMS_GMR(GVMS, TOKEN.token_BEARER_TOKEN, Notification_Box_Id, Notification_Message_Id, updateGMR) Then
                    GVMS.SAVE()
                End If
            End If
        End If


    End Function

    Shared Function GET_GVMS_LIST()

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then


            'Dim AccessToken = ""
            'grantAccess(AccessToken, "write:goods-movement-system", "AVISO")

            If TOKEN.token_BEARER_TOKEN <> "" Then
                If getGVMS_LIST(TOKEN.token_BEARER_TOKEN) Then
                    MsgBox("LISTE: " & Now.ToShortDateString & " " & Now.ToShortTimeString)
                End If
            End If
        End If
    End Function

    Shared Function GET_GVMS_GMR(GMR As String)

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then

            'Dim AccessToken = ""
            'grantAccess(AccessToken, "write:goods-movement-system", "AVISO")

            If TOKEN.token_BEARER_TOKEN <> "" Then
                If getGVMS_GMR(GMR, TOKEN.token_BEARER_TOKEN) Then
                    MsgBox("GMR: " & Now.ToShortDateString & " " & Now.ToShortTimeString)
                End If
            End If
        End If

    End Function


    Shared Function DELETE_GMR(GVMS As VERAG_PROG_ALLGEMEIN.cGVMS)

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then
            'Dim AccessToken = ""
            'grantAccess(TOKEN.token_BEARER_TOKEN, "write:goods-movement-system+read:pull-notifications", "AVISO")

            If TOKEN.token_BEARER_TOKEN <> "" Then
                Dim Notification_Box_Id = ""
                Dim Notification_Message_Id = ""
                If delGVMS_GMR(GVMS, TOKEN.token_BEARER_TOKEN, Notification_Box_Id, Notification_Message_Id) Then
                    'GVMS.delete()
                    MsgBox("GELÖSCHT: " & Now.ToShortDateString & " " & Now.ToShortTimeString)
                End If
            End If
        End If

    End Function

    Shared Function GET_NOTIFICATIONS(Notification_Box_Id As String) As Boolean
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then
            '      Dim AccessTokenNotTEST1 = grantAccessApplication("", "read:pull-notifications")
            ' If AccessTokenNotTEST1 <> "" Then
            getGVMS_Notifications(TOKEN.token_BEARER_TOKEN, Notification_Box_Id) 'Notification_Box_Id) '"877b619c-33c1-4ab6-a34f-8bd7542e0596"
        End If
    End Function
    Shared Function Acknowledge_NOTIFICATIONS(Notification_Box_Id As String, Notification_Message_Id As String) As Boolean
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then
            'Dim AccessTokenNotTEST1 = grantAccessApplication("", "write:notifications")
            '  If AccessTokenNotTEST1 <> "" Then
            ' MsgBox("4")
            getGVMS_AcknolageNotifications(TOKEN.token_BEARER_TOKEN, Notification_Box_Id, Notification_Message_Id) '"877b619c-33c1-4ab6-a34f-8bd7542e0596"
        End If
    End Function

    Shared Sub hmrcTEST2()
        'Dim rClient As RestClient = New RestClient()
        'rClient.endPoint = "https://test-api.service.hmrc.gov.uk/hello/user"
        'Dim strResponse As String = String.Empty
        'strResponse = rClient.makeRequest(_accessToken)

        Dim rest As New Chilkat.Rest

        '  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("https://test-api.service.hmrc.gov.uk", port, bTls, bAutoReconnect)
        '389356931 -> VERAG-UNISPED
        'Dim responseJson As String = rest.FullRequestNoBody("GET", "/organisations/vat/check-vat-number/lookup/553557881")
        'Dim responseJson As String = rest.FullRequestNoBody("GET", "/organisations/vat/check-vat-number/lookup/553552881") 'falsch
        Dim responseJson As String = rest.FullRequestNoBody("GET", "/organisations/vat/check-vat-number/lookup/5535532881") 'falsch
        If (rest.LastMethodSuccess <> True) Then
            Console.WriteLine(rest.LastErrorText)
            Exit Sub
        End If

        Try

            Dim read = Newtonsoft.Json.Linq.JObject.Parse(responseJson)

            If read.Item("code") IsNot Nothing Then
                Dim VAT_Message = read.Item("message").ToString
                Dim VAT_code = read.Item("code").ToString
                MsgBox("ERROR: " & VAT_Message, MsgBoxStyle.OkOnly, VAT_code)
            Else
                ' Dim json As String = "{""name"":""Rap God"",""statistics"":{""likeCount"":""122255"",""dislikeCount"":""4472""}}"
                Dim VAT_Name = read.Item("target")("name").ToString
                Dim VAT_processingDate = read.Item("processingDate").ToString
                Dim VAT_Strasse = read.Item("target")("address")("line1").ToString
                Dim VAT_PLZ = read.Item("target")("address")("postcode").ToString
                Dim VAT_countryCode = read.Item("target")("address")("countryCode").ToString

                MsgBox(VAT_Name)
                MsgBox(VAT_processingDate)
            End If
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try


        'Console.WriteLine(responseJson)
        'Console.WriteLine("----")

        ''  We can alternatively do this:
        'rest.ClearAllQueryParams()
        '' rest.AddQueryParam("consumer_key", "YOUR_CONSUMER_KEY")
        '' rest.AddQueryParam("consumer_secret", "YOUR_CONSUMER_SECRET")
        'responseJson = rest.FullRequestNoBody("GET", "/wp-json/wc/v1/products")
        'If (rest.LastMethodSuccess <> True) Then
        '    Console.WriteLine(rest.LastErrorText)
        '    Exit Sub
        'End If


        Console.WriteLine(responseJson)

    End Sub


    Shared Sub hmrcTEST()
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        '---------------------------REF DATA---------------------------

        getGVMS_RefData()

        '--------------------------------------------------------------


        Exit Sub


        '---------------------------NOTIFICATIONS---------------------------

        Dim TOKEN = cHMRC.getTOKEN("GVMS")

        If TOKEN.hasEntry Then
            '        Dim AccessTokenNotTEST1 = grantAccessApplication("", "read:pull-notifications")
            '  If AccessTokenNotTEST1 <> "" Then
            getGVMS_Notifications(TOKEN.token_BEARER_TOKEN, "877b619c-33c1-4ab6-a34f-8bd7542e0596")
        End If

        '-------------------------------------------------------------------
        Exit Sub


        '  Dim AccessToken = ""
        'grantAccess(AccessToken, "write:goods-movement-system")
        ' grantAccess(AccessToken, "write:goods-movement-system+read:pull-notifications", "AVISO")
        'getHMRC_Token(AccessToken, "write:goods-movement-system")

        ' MsgBox(AccessToken)
        'If AccessToken <> "" Then

        '    Dim Notification_Box_Id = ""
        '    Dim Notification_Message_Id = ""
        '    If genGVMS_GMR(AccessToken, Notification_Box_Id, Notification_Message_Id) Then

        '        Dim AccessTokenNotTEST = grantAccessApplication("", "read:pull-notifications")

        '        '  getHMRC_Token(AccessTokenNotTEST, "read:pull-notifications")
        '        ' grantAccess(AccessTokenNotTEST, "read:pull-notifications")
        '        If AccessTokenNotTEST <> "" Then
        '            getGVMS_Notifications(AccessTokenNotTEST, Notification_Box_Id)
        '        End If
        '        'If AccessToken <> "" Then
        '        '    getGVMS_Notifications(AccessToken, Notification_Box_Id)
        '        'End If
        '    End If
        'End If

        Exit Sub
        'UnlockCilkat()

        'Dim AccessTokenNotTEST = ""
        'grantAccess(AccessTokenNotTEST, "read:pull-notifications")
        'If AccessTokenNotTEST <> "" Then
        '    getGVMS_Notifications(AccessTokenNotTEST, "877b619c-33c1-4ab6-a34f-8bd7542e0596")

        'End If
        Exit Sub

        'Dim AccessToken = ""
        'grantAccess(AccessToken, "write:goods-movement-system")
        'If AccessToken <> "" Then

        '    Dim Notification_Box_Id = ""
        '    Dim Notification_Message_Id = ""
        '    genGVMS_GMR(AccessToken, Notification_Box_Id, Notification_Message_Id)

        '    Dim AccessTokenNot = ""
        '    grantAccess(AccessTokenNot, "read:pull-notifications")
        '    If AccessTokenNot <> "" Then
        '        getGVMS_Notifications(AccessTokenNot, Notification_Box_Id)

        '    End If
        'End If



        Exit Sub
        getGVMS_RefData()

        Exit Sub



        Exit Sub
        'genGVMS_GMR("TEST")

        'Exit Sub
        'Dim AccessToken = ""
        'grantAccess(AccessToken)
        'If AccessToken <> "" Then
        '    genGVMS_GMR(AccessToken)
        'End If
    End Sub
    Shared Sub grantAccess(ByRef AccessToken, ByRef RefreshToken, scope, HMRC_APPLICATION)
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            Dim CREDENTIALS = getCredentials(HMRC_APPLICATION)

            Debug.WriteLine("HMRC Start")
            Dim oauth2 As Chilkat.OAuth2 = New Chilkat.OAuth2()
            Dim success As Boolean

            oauth2.ListenPort = 3017
            oauth2.AuthorizationEndpoint = CREDENTIALS.API_STRING & "/oauth/authorize"
            oauth2.TokenEndpoint = CREDENTIALS.API_STRING & "/oauth/token"
            oauth2.ClientId = CREDENTIALS.CLIENT_ID '"xybTOMaQWcuifeW5xnGggojlACWC"
            oauth2.ClientSecret = CREDENTIALS.CLIENT_SECRET '"bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1" 
            oauth2.Scope = scope '"write:goods-movement-system"

            'oauth2.RedirectAllowHtml = "http://www.verag.ag/AVISO/Success.html"
            'oauth2.RedirectDenyHtml = "http://www.verag.ag/AVISO/Sussess.html"


            Dim url As String = oauth2.StartAuth()
            MsgBox(url)



            'oauth2.AuthorizationEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/authorize"
            'oauth2.TokenEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/token"



            If oauth2.LastMethodSuccess <> True Then
                Debug.WriteLine(oauth2.LastErrorText)
                Exit Sub
            End If

            Dim http As Chilkat.Http = New Chilkat.Http()

            Dim useBrowser = False
            If Not useBrowser Then
                System.Diagnostics.Process.Start(url)
                Dim numMsWaited As Integer = 0


                While (numMsWaited < 120000) AndAlso (oauth2.AuthFlowState < 3)
                    oauth2.SleepMs(100)
                    numMsWaited = numMsWaited + 100
                End While
                ' If there was no response from the browser within 30 seconds, then 
                ' the AuthFlowState will be equal to 1 Or 2.
                ' 1: Waiting for Redirect. The OAuth2 background thread Is waiting to receive the redirect HTTP request from the browser.
                ' 2: Waiting for Final Response. The OAuth2 background thread Is waiting for the final access token response.
                ' In that case, cancel the background task started in the call to StartAuth.

            Else

                '   System.Diagnostics.Process.Start(url)

                Dim f As New Form
                f.Size = New Size(800, 1400)
                Dim wb As New WebBrowser
                f.Controls.Add(wb)
                f.StartPosition = FormStartPosition.CenterScreen
                wb.Dock = DockStyle.Fill
                wb.Navigate(url)
                Dim done = False


                'AddHandler wb.DocumentCompleted, Sub()
                '                                     If Not done Then

                '                                         If wb.Url.AbsolutePath = "/api-test-login/sign-in" Then
                '                                             Try
                '                                                 Dim txtInput As HtmlElement = wb.Document.Forms(0).GetElementsByTagName("input").GetElementsByName("userId")(0)
                '                                                 txtInput.InnerText = "224015321897"
                '                                                 Dim txtInputPwd As HtmlElement = wb.Document.Forms(0).GetElementsByTagName("input").GetElementsByName("password")(0)
                '                                                 txtInputPwd.InnerText = "ry1cspz0nsvj"
                '                                                 done = True
                '                                             Catch
                '                                             End Try
                '                                         End If
                '                                     End If
                '                                     MsgBox(wb.Url.AbsolutePath)
                '                                 End Sub

                f.ShowDialog()
            End If



            If oauth2.AuthFlowState < 3 Then
                oauth2.Cancel()
                Debug.WriteLine("No response from the browser!")
                Exit Sub
            End If

            Debug.WriteLine("HMRC here")


            ' Check the AuthFlowState to see if authorization was granted, denied, Or if some error occurred
            ' The possible AuthFlowState values are:
            ' 3 Completed with Success. The OAuth2 flow has completed, the background thread exited, And the successful JSON response Is available in AccessTokenResponse property.
            ' 4: Completed with Access Denied. The OAuth2 flow has completed, the background thread exited, And the error JSON Is available in AccessTokenResponse property.
            ' 5: Failed Prior To Completion. The OAuth2 flow failed To complete, the background thread exited, And the error information Is available in the FailureInfo property.

            If oauth2.AuthFlowState = 5 Then
                Debug.WriteLine("OAuth2 failed to complete.")
                Debug.WriteLine(oauth2.FailureInfo)
                Exit Sub
            End If

            If oauth2.AuthFlowState = 4 Then
                Debug.WriteLine("OAuth2 authorization was denied.")
                Debug.WriteLine(oauth2.AccessTokenResponse)
                Exit Sub
            End If

            If oauth2.AuthFlowState <> 3 Then
                Debug.WriteLine("Unexpected AuthFlowState:" & Convert.ToString(oauth2.AuthFlowState))
                Exit Sub
            End If

            '  MsgBox("OAuth2 authorization granted!")
            Debug.WriteLine("OAuth2 authorization granted!")
            Debug.WriteLine("Access Token = " & oauth2.AccessToken)
            Debug.WriteLine("Refresh Token = " & oauth2.RefreshToken)
            Dim json As Chilkat.JsonObject = New Chilkat.JsonObject()
            json.Load(oauth2.AccessTokenResponse)
            json.EmitCompact = False
            Debug.WriteLine(json.Emit())
            '    MsgBox(json.Emit())

            ' The JSON response looks Like this

            ' {
            '   "token_type": "Bearer",
            '   "scope": "user_impersonation",
            '   "expires_in": "3599",
            '   "ext_expires_in": "0",
            '   "expires_on": "1524783438",
            '   "not_before": "1524779538",
            '   "resource": "https://mydomain.api.crm.dynamics.com",
            '   "access_token": "...",
            '   "refresh_token": "...",
            '   "id_token": "..."
            ' }

            ' If an "expires_on" member does Not exist, then add the JSON member by
            ' getting the current system date/time And adding the "expires_in" seconds.
            ' This way we'll know when the token expires.

            If json.HasMember("expires_on") <> True Then
                Dim dtExpire As Chilkat.CkDateTime = New Chilkat.CkDateTime()
                dtExpire.SetFromCurrentSystemTime()
                dtExpire.AddSeconds(json.IntOf("expires_in"))
                json.AppendString("expires_on", dtExpire.GetAsUnixTimeStr(False))
            End If

            Debug.WriteLine(json.Emit())
            Dim fac As Chilkat.FileAccess = New Chilkat.FileAccess()
            'fac.WriteEntireTextFile("qa_data/tokens/hmrc.json", json.Emit(), "utf-8", False)
            '  fac.WriteEntireTextFile("C:\Users\DEVELOPER1\Desktop\hmrc.json", json.Emit(), "utf-8", False)
            AccessToken = oauth2.AccessToken
            RefreshToken = oauth2.RefreshToken



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


    Shared Sub HMRC_RefreshToken(ByRef TOKEN As cHMRCToken, HMRC_APPLICATION As String)

        If DateDiff(DateInterval.Minute, TOKEN.token_accestoken_datetime, Now) < 230 Then 'bis 240 MIN / 4hr 
            'Token ist noch frisch
            Exit Sub
        End If

        ' Chilkat Lizenz aktivieren (falls benötigt)
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        ' HTTP-Objekt für API-Request erstellen
        Dim http As New Chilkat.Http()

        ' URL für HMRC Token Refresh
        ' Dim url As String = "/oauth/token"

        ' HTTP-Request-Objekt für POST-Anfrage
        Dim req As New Chilkat.HttpRequest()
        req.HttpVerb = "POST"
        req.Path = "/oauth/token"
        req.ContentType = "application/x-www-form-urlencoded"

        ' OAuth2 Credentials einfügen
        Dim CREDENTIALS = getCredentials(HMRC_APPLICATION)


        req.AddParam("client_secret", CREDENTIALS.CLIENT_SECRET)
        req.AddParam("client_id", CREDENTIALS.CLIENT_ID)
        req.AddParam("grant_type", "client_credentials")
        req.AddParam("refresh_token", TOKEN.token_REFRESH_TOKEN)



        '   rest.AddQueryParam("scope", scope)

        MsgBox(CREDENTIALS.API_STRING)
        ' Anfrage senden
        Dim resp As Chilkat.HttpResponse = http.PostUrlEncoded(CREDENTIALS.API_STRING & "/oauth/token", req)

        ' Fehlerprüfung
        If resp Is Nothing Then
            Console.WriteLine("Fehler: " & http.LastErrorText)
            Exit Sub
        End If

        ' API-Antwort ausgeben
        Dim json As New Chilkat.JsonObject()
        json.Load(resp.BodyStr)

        ' Neuer Access Token
        Dim accessToken As String = json.StringOf("access_token")
        Dim newRefreshToken As String = json.StringOf("refresh_token")
        Dim expiresIn As String = json.StringOf("expires_in")

        Console.WriteLine("Neuer Access Token: " & accessToken)
        Console.WriteLine("Neuer Refresh Token: " & newRefreshToken)
        Console.WriteLine("Gültigkeit (Sekunden): " & expiresIn)

        ' Optional: Tokens in einer Datei speichern
        'Dim tokenFile As String = "token.json"
        'json.EmitCompact = False
        'json.WriteFile(tokenFile)

        TOKEN.token_REFRESH_TOKEN = newRefreshToken
        TOKEN.token_BEARER_TOKEN = accessToken
        TOKEN.token_accestoken_datetime = Now
        TOKEN.SAVE()

        Console.WriteLine("Tokens wurden in TokenDB gespeichert.")

    End Sub


    Shared Function grantAccessApplication(ByRef AccessToken, scope) As String
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            Dim rest As New Chilkat.Rest
            Dim success As Boolean


            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)
                MsgBox(rest.LastErrorText)
                Return ""
            End If


            rest.AddHeader("Content-Type", "application/x-www-form-urlencoded")

            rest.AddQueryParam("client_secret", CLIENT_SECRET)
            rest.AddQueryParam("client_id", CLIENT_ID)
            rest.AddQueryParam("grant_type", "client_credentials")
            rest.AddQueryParam("scope", scope)


            Dim ResponseStr = rest.FullRequestFormUrlEncoded("POST", "/oauth/token")

            Dim respStatusCode As Integer = rest.ResponseStatusCode


            If (respStatusCode <> 200) Then
                Debug.WriteLine(rest.LastErrorText)
                Return ""
            End If

            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.Load(ResponseStr)

            AccessToken = jsonResp.StringOf("access_token")
            '   MsgBox("AccessToken: " & AccessToken)
            'jsonResp.StringOf("expires_in")

            Return AccessToken
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""

    End Function


    Shared Sub VATTEST(hmrc_app_server_token)

        Dim rest As New Chilkat.Rest
        Dim success As Boolean


        Dim bTls As Boolean = True
        Dim port As Integer = 443
        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)
            Exit Sub
        End If


        '  See the Online Tool for Generating JSON Creation Code
        Dim json As New Chilkat.JsonObject
        json.UpdateString("periodKey", "#001")
        json.UpdateNumber("vatDueSales", "100.00")
        json.UpdateNumber("vatDueAcquisitions", "100.00")
        json.UpdateNumber("totalVatDue", "200")
        json.UpdateNumber("vatReclaimedCurrPeriod", "100.00")
        json.UpdateNumber("netVatDue", "100")
        json.UpdateNumber("totalValueSalesExVAT", "500")
        json.UpdateNumber("totalValuePurchasesExVAT", "500")
        json.UpdateNumber("totalValueGoodsSuppliedExVAT", "500")
        json.UpdateNumber("totalAcquisitionsExVAT", "500")
        json.UpdateBool("finalised", True)


        rest.AddHeader("Content-Type", "application/json")
        rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
        rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

        Dim sbRequestBody As New Chilkat.StringBuilder
        json.EmitSb(sbRequestBody)
        Dim sbResponseBody As New Chilkat.StringBuilder
        success = rest.FullRequestSb("POST", "/organisations/vat/123456789/returns", sbRequestBody, sbResponseBody)
        If (success <> True) Then
            Debug.WriteLine(rest.LastErrorText)
            Exit Sub
        End If

        Dim respStatusCode As Integer = rest.ResponseStatusCode
        If (respStatusCode >= 400) Then
            Debug.WriteLine("Response Status Code = " & respStatusCode)
            Debug.WriteLine("Response Header:")
            Debug.WriteLine(rest.ResponseHeader)
            Debug.WriteLine("Response Body:")
            Debug.WriteLine(sbResponseBody.GetAsString())
            Exit Sub
        End If


    End Sub

    Shared Sub getGVMS_RefData()

        Dim rest As New Chilkat.Rest
        Dim success As Boolean

        Dim bTls As Boolean = True
        Dim portSSL As Integer = 443
        Dim bAutoReconnect As Boolean = True

        success = rest.Connect(API_STRING, portSSL, bTls, bAutoReconnect)
        If (success <> True) Then
            Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
            Debug.WriteLine(rest.LastErrorText)

            Exit Sub
        End If

        rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

        Dim sbRequestBody As New Chilkat.StringBuilder

        Dim sbResponseBody As New Chilkat.StringBuilder
        success = rest.FullRequestSb("GET", "/customs/goods-movement-system/reference-data", sbRequestBody, sbResponseBody)

        If (success <> True) Then
            Debug.WriteLine(rest.LastErrorText)
            MsgBox(rest.LastErrorText)
            Exit Sub
        End If

        Dim respStatusCode As Integer = rest.ResponseStatusCode
        If (respStatusCode <> 200) Then
            MsgBox("respStatusCode: " & respStatusCode)
            Debug.WriteLine("Response Status Code = " & respStatusCode)
            Debug.WriteLine("Response Header:")
            Debug.WriteLine(rest.ResponseHeader)
            Debug.WriteLine("Response Body:")
            Debug.WriteLine(sbResponseBody.GetAsString())

            Exit Sub
        End If

        MsgBox("OK " & respStatusCode)

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

        VERAG_PROG_ALLGEMEIN.cGVMS_Routes.DELETE_ALL()
        For i = 0 To jsonResp.SizeOfArray("routes") - 1

            Dim ROUTE As New VERAG_PROG_ALLGEMEIN.cGVMS_Routes

            ROUTE.routeId = jsonResp.StringOf("routes[" & i & "].routeId")
            ROUTE.routeDirection = jsonResp.StringOf("routes[" & i & "].routeDirection")

            ROUTE.routeEffectiveFrom = jsonResp.StringOf("routes[" & i & "].routeEffectiveFrom")
            ROUTE.departurePortId = jsonResp.StringOf("routes[" & i & "].departurePortId")
            ROUTE.arrivalPortId = jsonResp.StringOf("routes[" & i & "].arrivalPortId")
            ROUTE.carrierId = jsonResp.StringOf("routes[" & i & "].carrierId")
            ROUTE.routeEffectiveTo = jsonResp.StringOf("routes[" & i & "].routeEffectiveTo")
            ROUTE.SAVE()

        Next


        VERAG_PROG_ALLGEMEIN.cGVMS_Ports.DELETE_ALL()
        For i = 0 To jsonResp.SizeOfArray("ports") - 1

            Dim PORT As New VERAG_PROG_ALLGEMEIN.cGVMS_Ports
            PORT.portId = jsonResp.StringOf("ports[" & i & "].portId")
            PORT.portDescription = jsonResp.StringOf("ports[" & i & "].portDescription")
            PORT.portRegion = jsonResp.StringOf("ports[" & i & "].portRegion")
            PORT.portEffectiveFrom = jsonResp.StringOf("ports[" & i & "].portEffectiveFrom")
            PORT.portDescription = jsonResp.StringOf("ports[" & i & "].portDescription")
            PORT.chiefPortCode = jsonResp.StringOf("ports[" & i & "].chiefPortCode")
            PORT.cdsPortCode = jsonResp.StringOf("ports[" & i & "].cdsPortCode")
            PORT.officeOfTransitCustomsOfficeCode = jsonResp.StringOf("ports[" & i & "].officeOfTransitCustomsOfficeCode")
            PORT.portEffectiveTo = jsonResp.StringOf("ports[" & i & "].portEffectiveTo")
            PORT.portCountryCode = jsonResp.StringOf("ports[" & i & "].portCountryCode")
            PORT.isOperatingArrivedExportsProcess = jsonResp.StringOf("ports[" & i & "].isOperatingArrivedExportsProcess")
            PORT.SAVE()
        Next

        VERAG_PROG_ALLGEMEIN.cGVMS_Carriers.DELETE_ALL()
        For i = 0 To jsonResp.SizeOfArray("carriers") - 1

            Dim CARRIER As New VERAG_PROG_ALLGEMEIN.cGVMS_Carriers
            CARRIER.carrierId = jsonResp.StringOf("carriers[" & i & "].carrierId")
            CARRIER.carrierName = jsonResp.StringOf("carriers[" & i & "].carrierName")
            CARRIER.countryCode = jsonResp.StringOf("carriers[" & i & "].countryCode")
            CARRIER.SAVE()
        Next

        'For i = 0 To jsonResp.SizeOfArray("locations") - 1

        '    MsgBox(jsonResp.StringOf("locations[" & i & "].locationId"))
        '    MsgBox(jsonResp.StringOf("locations[" & i & "].locationDescription"))
        '    MsgBox(jsonResp.StringOf("locations[" & i & "].locationType"))

        'Next
        'For i = 0 To jsonResp.SizeOfArray("inspectionTypes") - 1

        '    MsgBox(jsonResp.StringOf("inspectionTypes[" & i & "].inspectionTypeId"))
        '    MsgBox(jsonResp.StringOf("inspectionTypes[" & i & "].description"))

        'Next
        'For i = 0 To jsonResp.SizeOfArray("ruleFailures") - 1

        '    MsgBox(jsonResp.StringOf("ruleFailures[" & i & "].ruleId"))
        '    MsgBox(jsonResp.StringOf("ruleFailures[" & i & "].ruleDescription"))

        'Next

        MsgBox("FERTIG:  " & Now.ToShortDateString & " " & Now.ToShortTimeString)

    End Sub
    Private Shared Function genGVMS_GMR(ByRef GVMS As VERAG_PROG_ALLGEMEIN.cGVMS, hmrc_app_server_token As String, ByRef Notification_Box_Id As String, ByRef Notification_Message_Id As String, Optional updateGMR As String = "") As Boolean
        Try
            Dim rest As New Chilkat.Rest
            Dim success As Boolean


            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)
                MsgBox(rest.LastErrorText)
                Return False
            End If

            '  See the Online Tool for Generating JSON Creation Code
            Dim json As New Chilkat.JsonObject
            json.UpdateString("direction", GVMS.gvms_direction)
            json.UpdateBool("isUnaccompanied", GVMS.gvms_isUnaccompanied)
            json.UpdateString("vehicleRegNum", GVMS.gvms_vehicleRegNum) 'LKW
            If If(GVMS.gvms_trailorRegNum, "") <> "" Then json.UpdateString("trailerRegistrationNums", GVMS.gvms_trailorRegNum) 'Anhänger


            json.UpdateString("plannedCrossing.routeId", GVMS.gvms_routeId) '-->  Calais - Dover - DFDS
            json.UpdateString("plannedCrossing.localDateTimeOfDeparture", Format(CDate(GVMS.gvms_locateDateTimeOfDeparture), "yyyy-MM-ddTHH:mm")) '"2021-08-11T10:58")



            If GVMS.gvms_empty Then
                json.UpdateBool("emptyVehicle.isOwnVehicle", GVMS.gvms_emptyisOwn)
                '   json.UpdateBool("emptyVehicle.sAndSMasterRefNum", GVMS.gvms_emptyisOwn) 
            Else
                Dim cnt = 0
                '---------customsDeclarations----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.IMPORT Or POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.EXPORT Then
                        json.UpdateString("customsDeclarations[" & cnt & "].customsDeclarationId", POS.gvms_RefNum)
                        '  json.UpdateString("customsDeclarations[" & cnt & "].customsDeclarationPartId", "20GB01I0XLM976S001")
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("customsDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next

                '---------transitDeclarations TSAD----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.TSAD Then
                        json.UpdateString("transitDeclarations[" & cnt & "].transitDeclarationId", POS.gvms_RefNum)
                        json.UpdateBool("transitDeclarations[" & cnt & "].isTSAD", True)
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("transitDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next

                '---------transitDeclarations TAD----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.TAD Then
                        json.UpdateString("transitDeclarations[" & cnt & "].transitDeclarationId", POS.gvms_RefNum)
                        json.UpdateBool("transitDeclarations[" & cnt & "].isTSAD", False)
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("transitDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next

                '---------tirDeclarations----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.TIR Then
                        json.UpdateString("tirDeclarations[" & cnt & "].tirCarnetId", POS.gvms_RefNum)
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("tirDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next

                '---------ataDeclarations----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.ATA Then
                        json.UpdateString("ataDeclarations[" & cnt & "].ataCarnetId", POS.gvms_RefNum)
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("ataDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next


                '---------eidrDeclarations----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.EIDR Then
                        json.UpdateString("eidrDeclarations[" & cnt & "].traderEORI", POS.gvms_RefNum)
                        If If(POS.gvms_SS, "") <> "" Then json.UpdateString("eidrDeclarations[" & cnt & "].sAndSMasterRefNum", POS.gvms_SS)
                    End If
                    cnt += 1
                Next


                '---------indirectExportDeclarations----------------
                cnt = 0
                For Each POS In GVMS.GVMS_POSITIONEN
                    If POS.gvms_art = VERAG_PROG_ALLGEMEIN.cGVMS_POS_DecArt.INDIRECT Then
                        json.UpdateString("indirectExportDeclarations[" & cnt & "].eadMasterRefNum", POS.gvms_RefNum)
                    End If
                    cnt += 1
                Next

            End If


            rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

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


            Dim sbResponseBody As New Chilkat.StringBuilder

            If updateGMR <> "" Then 'UPDATE!
                success = rest.FullRequestSb("PUT", "/customs/goods-movement-system/movements/" & updateGMR, sbRequestBody, sbResponseBody)
                Dim respStatusCode As Integer = rest.ResponseStatusCode

                If (respStatusCode = 404) Then 'update
                    MsgBox("GMR wurde nicht gefunden.")
                    Return False
                End If
                '403
                If (respStatusCode = 202) Then
                    MsgBox("UPDATE: " & Now.ToShortDateString & " " & Now.ToShortTimeString)

                    Return True 'OK
                Else
                    MsgBox("HMRC ERROR: " & respStatusCode & rest.ResponseHeader.ToString)
                    MsgBox("HMRC ERROR: " & sbResponseBody.ToString)
                    Return False
                End If

            Else
                success = rest.FullRequestSb("POST", "/customs/goods-movement-system/movements", sbRequestBody, sbResponseBody)


                If (success <> True) Then
                    Debug.WriteLine(rest.LastErrorText)
                    Return False
                End If
                Dim respStatusCode As Integer = rest.ResponseStatusCode

                If (respStatusCode = 404) Then 'update
                    MsgBox("GMR wurde nicht gefunden.")
                    Return False
                End If

                If (respStatusCode <> 202) Then
                    MsgBox("HMRC ERROR: " & respStatusCode & rest.ResponseHeader.ToString)
                    MsgBox("HMRC ERROR: " & sbResponseBody.ToString)
                    Return False
                End If



                'Dim jsonResp = New Chilkat.JsonObject()
                'jsonResp.Load(rest.ResponseHeader)


                'MsgBox(rest.ResponseHeader)

                'MsgBox(jsonResp.StringOf("Notification-Box-Id"))
                'MsgBox(jsonResp.StringOf("Notification-Message-Id"))

                'Notification_Box_Id = (jsonResp.StringOf("Notification-Box-Id"))
                'Notification_Message_Id = (jsonResp.StringOf("Notification-Message-Id"))

                For Each rh In rest.ResponseHeader.Split(vbNewLine)
                    If (rh.Contains("Notification-Box-Id: ")) Then
                        Notification_Box_Id = rh.Replace("Notification-Box-Id: ", "").Replace(vbNewLine, "").Replace(" ", "").Trim
                        ' MsgBox(Notification_Box_Id)
                    End If
                    If (rh.Contains("Notification-Message-Id: ")) Then
                        Notification_Message_Id = rh.Replace("Notification-Message-Id: ", "").Replace(vbNewLine, "").Replace(" ", "").Trim
                        '     MsgBox(Notification_Message_Id)
                    End If
                Next

                GVMS.gvms_notification_id = Notification_Message_Id
                GVMS.gvms_notification_boxid = Notification_Box_Id

                Return True
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function


    Private Shared Function delGVMS_GMR(ByRef GVMS As VERAG_PROG_ALLGEMEIN.cGVMS, hmrc_app_server_token As String, ByRef Notification_Box_Id As String, ByRef Notification_Message_Id As String) As Boolean
        Try
            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)
                MsgBox(rest.LastErrorText)
                Return False
            End If

            '  See the Online Tool for Generating JSON Creation Code
            Dim json As New Chilkat.JsonObject

            ' rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

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


            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("DELETE", "/customs/goods-movement-system/movements/" & GVMS.gvms_GMR, sbRequestBody, sbResponseBody)
            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return False
            End If
            Dim respStatusCode As Integer = rest.ResponseStatusCode

            If (respStatusCode = 404) Then
                MsgBox("GMR wurde nicht gefunden.")
                Return False
            End If
            If (respStatusCode <> 202) Then
                MsgBox("HMRC ERROR: " & respStatusCode & rest.ResponseHeader.ToString)
                Return False
            End If


            For Each rh In rest.ResponseHeader.Split(vbNewLine)
                If (rh.Contains("Notification-Box-Id: ")) Then
                    Notification_Box_Id = rh.Replace("Notification-Box-Id: ", "").Replace(vbNewLine, "").Replace(" ", "").Trim
                    ' MsgBox(Notification_Box_Id)
                End If
                If (rh.Contains("Notification-Message-Id: ")) Then
                    Notification_Message_Id = rh.Replace("Notification-Message-Id: ", "").Replace(vbNewLine, "").Replace(" ", "").Trim
                    '     MsgBox(Notification_Message_Id)
                End If
            Next

            GVMS.gvms_notification_id = Notification_Message_Id
            GVMS.gvms_notification_boxid = Notification_Box_Id

            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function


    Private Shared Function getGVMS_LIST(hmrc_app_server_token As String) As Boolean
        Try
            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)
                MsgBox(rest.LastErrorText)
                Return False
            End If

            '  See the Online Tool for Generating JSON Creation Code
            Dim json As New Chilkat.JsonObject

            ' rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

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


            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("GET", "/customs/goods-movement-system/movements", sbRequestBody, sbResponseBody)

            MsgBox("GO " & success)

            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return False
            End If
            Dim respStatusCode As Integer = rest.ResponseStatusCode


            If (respStatusCode = 200) Then
                MsgBox(sbResponseBody.ToString)
                Return True
            Else
                MsgBox(sbResponseBody.ToString)
                MsgBox(rest.ResponseHeader.ToString)
                MsgBox("HMRC ERROR: " & respStatusCode & rest.ResponseHeader.ToString)
                Return False
            End If


            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function


    Private Shared Function getGVMS_GMR(GMR As String, hmrc_app_server_token As String) As Boolean
        Try
            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)
                MsgBox(rest.LastErrorText)
                Return False
            End If

            '  See the Online Tool for Generating JSON Creation Code
            Dim json As New Chilkat.JsonObject

            ' rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

            Dim sbRequestBody As New Chilkat.StringBuilder


            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("GET", "/customs/goods-movement-system/movements/" & GMR, sbRequestBody, sbResponseBody)
            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return False
            End If
            Dim respStatusCode As Integer = rest.ResponseStatusCode


            If (respStatusCode = 200) Then
                MsgBox(sbResponseBody.ToString)
                Return True
            Else
                MsgBox("HMRC ERROR: " & respStatusCode & rest.ResponseHeader.ToString)
                Return False
            End If


            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function


    Private Shared Sub getGVMS_Notifications(hmrc_app_server_token As String, Notification_Box_Id As String)
        Try


            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)

                Exit Sub
            End If
            '37d1feab8776c006f7fb7c9cc2f93172


            '"UK_INBOUND",
            '      "UK_OUTBOUND",
            '      "GB_TO_NI",
            '      "NI_TO_GB"

            '  See the Online Tool for Generating JSON Creation Code
            'Dim json As New Chilkat.JsonObject
            'json.UpdateString("boxId", Notification_Box_Id)
            ' json.UpdateString("status", "PENDING")
            'json.UpdateString("fromDate", "2020-06-03T14:20:54.987")
            'json.UpdateString("toDate", "2020-06-03T14:20:54.987")


            ' rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")


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


            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("GET", "/misc/push-pull-notification/box/" & Notification_Box_Id & "/notifications", sbRequestBody, sbResponseBody)

            Dim respStatusCode As Integer = rest.ResponseStatusCode


            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Exit Sub
            End If
            If (respStatusCode <> 200) Then
                System.IO.File.WriteAllText("C:\Users\DEVELOPER1\Desktop\hmrc3.json", rest.ResponseHeader.ToString())

                Debug.WriteLine("Response Status Code = " & respStatusCode)
                Debug.WriteLine("Response Header:")
                Debug.WriteLine(rest.ResponseHeader)
                Debug.WriteLine("Response Body:")
                Debug.WriteLine(sbResponseBody.GetAsString())
                Exit Sub
            End If

            Dim strJson = sbResponseBody.ToString

            If strJson.StartsWith("[") Then
                strJson = "{""arrNotification"":" & strJson & "}"
            End If

            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.Load(strJson)



            For i = 0 To jsonResp.SizeOfArray("arrNotification") - 1

                'MsgBox(jsonResp.StringOf("arrNotification[" & i & "].status"))
                'Dim notificationId = jsonResp.StringOf("arrNotification[" & i & "].notificationId")
                'If notificationId = "notificationId" Then
                '    MsgBox("OOOO")
                'End If

                Dim jsonRespMsg = New Chilkat.JsonObject()
                If jsonRespMsg.Load(jsonResp.StringOf("arrNotification[" & i & "].message")) Then
                    If jsonRespMsg.StringOf("gmrId") <> "" Then
                        Dim notificationId = jsonRespMsg.StringOf("messageId")
                        Dim GVMS = VERAG_PROG_ALLGEMEIN.cGVMS.LOAD_ByNotification(Notification_Box_Id, notificationId)
                        If GVMS IsNot Nothing Then
                            If jsonRespMsg.StringOf("gmrId") <> "" Then GVMS.gvms_GMR = jsonRespMsg.StringOf("gmrId")
                            If jsonRespMsg.StringOf("gmrState") <> "" Then GVMS.gvms_status = jsonRespMsg.StringOf("gmrState")
                            GVMS.SAVE()
                        End If
                    End If
                End If

                ' MsgBox(jsonRespMsg.StringOf("messageId") & " / " & jsonRespMsg.StringOf("gmrId") & " / " & jsonRespMsg.StringOf("gmrState"))


            Next

            'i = 0;
            'count_i = json.SizeOfArray("product.variants");
            'while (i < count_i) {
            '    json.I = i;
            '    id = json.IntOf("product.variants[i].id");
            '    product_id = json.IntOf("product.variants[i].product_id");
            '    title = json.StringOf("product.variants[i].title");
            '    price = json.StringOf("product.variants[i].price");
            '    sku = json.StringOf("product.variants[i].sku");
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub

    Private Shared Sub getGVMS_AcknolageNotifications(hmrc_app_server_token As String, Notification_Box_Id As String, Notification_Message_Id As String)
        Try


            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            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)

                Exit Sub
            End If

            ' rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
            rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")



            Dim json As New Chilkat.JsonObject
            json.Load("{
                          ""notificationIds"": [
                            """ & Notification_Message_Id & """
                          ]
                        }")

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


            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("PUT", "/misc/push-pull-notification/box/" & Notification_Box_Id & "/notifications/acknowledge", sbRequestBody, sbResponseBody)

            Dim respStatusCode As Integer = rest.ResponseStatusCode

            MsgBox("OK: " & success)
            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Exit Sub
            End If
            If (respStatusCode = 204) Then
                MsgBox("ACKNOLAGED " & Now.ToShortDateString & " " & Now.ToShortTimeString)
                Exit Sub
            Else
                System.IO.File.WriteAllText("C:\Users\DEVELOPER1\Desktop\hmrc3.json", rest.ResponseHeader.ToString())

                Debug.WriteLine("Response Status Code = " & respStatusCode)
                Debug.WriteLine("Response Header:")
                Debug.WriteLine(rest.ResponseHeader)
                Debug.WriteLine("Response Body:")
                Debug.WriteLine(sbResponseBody.GetAsString())
                Exit Sub
            End If


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


    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '''
    'Shared Sub testToken2()
    '    Dim refresh_token As String
    '    Dim token As String

    '    ' construct the request for access token
    '    Dim client = New RestClient(API_STRING & "/oauth/token")
    '    Dim request = New RestRequest("dfe/application-info", Method.POST)
    '    request.AddHeader("content-type", "application/x-www-form-urlencoded")
    '    request.AddParameter("grant_type", "client_credentials")
    '    request.AddParameter("client_id", "<Paste-your-client-id-here>")
    '    request.AddParameter("client_secret", "<Paste-your-client-secret-here>")

    '    ' make call to get token
    '    Dim response As IRestResponse = client.Execute(request)

    '    ' Extract token
    '    token = JObject.Parse(response.Content).SelectToken("$..access_token").ToString()
    '    refresh_token = JObject.Parse(response.Content).SelectToken("$..refresh_token").ToString()
    'End Sub
    Shared Sub getHMRC_Token(ByRef AccessToken, scope)
        'oauth2.ListenPort = 3017
        ''oauth2.AuthorizationEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/authorize"
        ''oauth2.TokenEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/token"
        'oauth2.AuthorizationEndpoint = API_STRING & "/oauth/authorize"
        'oauth2.TokenEndpoint = API_STRING & "/oauth/token"
        'oauth2.ClientId = "xybTOMaQWcuifeW5xnGggojlACWC"
        'oauth2.ClientSecret = "bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1"
        ''oauth2.Scope = "read:vat write:vat" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        'oauth2.Scope = scope '"write:goods-movement-system"
        'Dim url As String = oauth2.StartAuth()


        ' Refer to the documentation for more information on how to get the client id/secret
        'Dim clientId As String = "xybTOMaQWcuifeW5xnGggojlACWC"
        ' Dim clientSecret As String = "bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1"
        ' Refer to the documentation for more information on how to get the tokens
        'Dim accessToken As String = "" '"OaOXXXXTaSucp8XXcgXXH"
        ' Dim refreshToken As String = "kE4HXXXXXXXhxvtUHlboSF"

        ' -- Refresh the access token
        Dim request As System.Net.WebRequest = System.Net.HttpWebRequest.Create(API_STRING & "/oauth/token")
        'oauth2.AuthorizationEndpoint = API_STRING & "/oauth/authorize"
        ' oauth2.TokenEndpoint = API_STRING & "/oauth/token"
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        'request.ContentType = "application/json"

        Dim outgoingQueryString As NameValueCollection = HttpUtility.ParseQueryString(String.Empty)
        outgoingQueryString.Add("grant_type", "client_credentials")
        ' outgoingQueryString.Add("refresh_token", refreshToken)
        outgoingQueryString.Add("client_id", CLIENT_ID)
        outgoingQueryString.Add("client_secret", CLIENT_SECRET)
        outgoingQueryString.Add("scope", scope) '"write:goods-movement-system")
        Dim postBytes As Byte() = New ASCIIEncoding().GetBytes(outgoingQueryString.ToString())

        Dim postStream As Stream = request.GetRequestStream()
        postStream.Write(postBytes, 0, postBytes.Length)
        postStream.Flush()
        postStream.Close()
        Try

            Using response As System.Net.WebResponse = request.GetResponse()
                Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
                    ' Parse the JSON the way you prefer
                    'FFFFFFFFFFFFFFFFFFALSE::::::::::::::::::::::::  Dim jsonResult As RefreshTokenResultJSON = New System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(streamReader.ReadToEnd(), GetType(RefreshTokenResultJSON))
                    'FFFFFFFFFFFFFFFFFFALSE::::::::::::::::::::::::     AccessToken = jsonResult.access_token


                    ' For more information, refer to the documentation
                End Using
            End Using

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        '' -- Get current user profile
        'request = System.Net.HttpWebRequest.Create("https://api.clicdata.com/profile/user")
        'request.Method = "GET"
        'request.Headers.Add("Authorization", "Bearer " & accessToken)
        'Using response As System.Net.WebResponse = request.GetResponse()
        '    Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
        '        Dim jsonResponseText = streamReader.ReadToEnd()
        '        ' Parse the JSON the way you prefer
        '        ' In this example the JSON will be something Like:
        '        ' {"email_address" "john.smith@clicdata.com", "first_name": "John", "last_login_date": "2016−04−26T14:24:58+00:00", "last_name": "Smith", ...
        '        ' For more information, refer to the documentation
        '    End Using
        'End Using

        '' -- List the current data
        'request = System.Net.HttpWebRequest.Create("https://api.clicdata.com/data/")
        'request.Method = "GET"
        'request.Headers.Add("Authorization", "Bearer " & accessToken)
        'Using response As System.Net.WebResponse = request.GetResponse()
        '    Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
        '        Dim jsonResponseText = streamReader.ReadToEnd()
        '        ' Parse the JSON the way you prefer
        '        ' In this example the JSON will be something Like:
        '        ' { "count" 265, "data": [{ "description": "","source": "merge", "creation_date": "2015−06−10T12:47:32+02:00", "last_data_update_date": "2015−06−10T12:47:49+02:00", ...
        '        ' For more information, refer to the documentation
        '    End Using
        'End Using

        '' -- Create some new data
        'Dim dataId As Integer = 0
        'request = System.Net.HttpWebRequest.Create("https://api.clicdata.com/data/")
        'request.Method = "POST"
        'request.ContentType = "application/json"
        'request.Headers.Add("Authorization", "Bearer " & accessToken)
        'Using tStreamWriter As System.IO.StreamWriter = New System.IO.StreamWriter(request.GetRequestStream())
        '    tStreamWriter.Write(New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(New With {Key .name = "my test data " & Guid.NewGuid().ToString(), Key .description = "some description for my test data", Key .columns = {New With {Key .name = "column 1", Key .data_type = "text"}, New With {Key .name = "column 2", Key .data_type = "number"}}}))
        'End Using

        'Using response As System.Net.WebResponse = request.GetResponse()
        '    Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
        '        Dim jsonResponseText = streamReader.ReadToEnd()
        '        ' The JSON returned in this example is the ID of our newly created data
        '        dataId = Integer.Parse(jsonResponseText)
        '        ' For more information, refer to the documentation
        '    End Using
        'End Using

        '' -- Add a few rows of data
        'request = System.Net.HttpWebRequest.Create("https://api.clicdata.com/data/" & dataId & "/rows")
        'request.Method = "POST"
        'request.ContentType = "application/json"
        'request.Headers.Add("Authorization", "Bearer " & accessToken)
        'Using tStreamWriter As System.IO.StreamWriter = New System.IO.StreamWriter(request.GetRequestStream())
        '    tStreamWriter.Write(New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(New With {Key .data = New Object() {New Object() {"one", 1}, New Object() {"two", 2}}}))
        'End Using

        'Using response As System.Net.WebResponse = request.GetResponse()
        '    Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
        '        Dim jsonResponseText = streamReader.ReadToEnd()
        '        ' The JSON returned in this example tells us if the rows were inserted successfully:
        '        ' { "success" true }
        '        ' For more information, refer to the documentation
        '    End Using
        'End Using





    End Sub



    Shared Function getTOKEN(APPLICATION, Optional forceNewToken = False) As cHMRCToken

        Dim TOKEN = New cHMRCToken(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, APPLICATION)
        Try
            Dim appl = ""
            Dim HMRC_APPLICATION = "AVISO"
            Select Case APPLICATION
                Case "HELLOWORLD" '"EORI_CHECK"
                    'appl = "write:import-control-system+read:import-control-system"
                    appl = "applicationRestricted"
                    HMRC_APPLICATION = "AVISO"
                Case "GVMS"
                    appl = "write:goods-movement-system+read:pull-notifications"
                    HMRC_APPLICATION = "AVISO"
                Case "VAT_CHECK" '"EORI_CHECK"
                    appl = "read:vat write:vat"
                    HMRC_APPLICATION = "AVISO"
                Case "ENS" '"EORI_CHECK"
                    'appl = "write:import-control-system+read:import-control-system"
                    appl = "write:import-control-system"
                    HMRC_APPLICATION = "AVISO_ENS"
                Case "ENS_HELLOWORLD" '"EORI_CHECK"
                    'appl = "write:import-control-system+read:import-control-system"
                    appl = "hello"
                    HMRC_APPLICATION = "AVISO_ENS"
            End Select



            If forceNewToken OrElse TOKEN.hasEntry = False OrElse TOKEN.token_BEARER_TOKEN Is Nothing OrElse TOKEN.token_BEARER_TOKEN = "" Then
                'Neuer Token  
                Dim AccessToken = ""
                Dim RefreshToken = ""
                grantAccess(AccessToken, RefreshToken, appl, HMRC_APPLICATION)
                TOKEN.token_Application = APPLICATION
                TOKEN.token_BEARER_TOKEN = AccessToken
                TOKEN.token_REFRESH_TOKEN = RefreshToken
                TOKEN.token_refresh_datetime = Now
                TOKEN.token_accestoken_datetime = Now
                TOKEN.SAVE()
            Else
                'Refresh
                HMRC_RefreshToken(TOKEN, HMRC_APPLICATION)
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return TOKEN
    End Function


    Shared Function checkEORI_UK(eoriNumber As String, ByVal response As String) As Boolean
        ' Chilkat-Objekt initialisieren
        Dim http As New Chilkat.Http

        http.SetRequestHeader("Accept", "application/x-www-form-urlencoded")

        ' EORI-Nummer für die Überprüfung
        'Dim eoriNumber As String = "GB123456789000"
        Dim url As String = "https://api.service.hmrc.gov.uk/customs/eori/lookup/check-multiple-eori"


        Dim requestBody As New Chilkat.JsonObject
        requestBody.AppendArray("eoris").AddStringAt(-1, eoriNumber)
        requestBody.AppendArray("eoris").AddStringAt(-1, "GB8392848394939")



        ' HTTP GET-Anfrage senden
        Dim responseHttp = http.PostJson2(url, "application/json", requestBody.Emit())

        ' Fehlerprüfung
        If http.LastMethodSuccess <> True Then
            Console.WriteLine("Fehler: " & http.LastErrorText)
            Return False
        End If
        response = responseHttp.BodyStr
        ' Antwort ausgeben
        Console.WriteLine("API Antwort: " & responseHttp.BodyStr)
        Return True
    End Function

    Shared Function checkVAT_UK(VATNumber As String, ByVal response As String) As Boolean
        ' Chilkat-Objekt initialisieren
        Dim http As New Chilkat.Http

        ' Falls API-Schlüssel oder Authentifizierung erforderlich ist, hinzufügen
        ' Beispiel: http.SetRequestHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN")

        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

        Dim TOKEN = getTOKEN("VAT_CHECK")

        If TOKEN.hasEntry Then
            http.SetRequestHeader("Authorization", "Bearer " & TOKEN.token_BEARER_TOKEN)
            http.SetRequestHeader("Accept", "application/x-www-form-urlencoded")

            ' EORI-Nummer für die Überprüfung  
            Dim url As String = "https://api.service.hmrc.gov.uk/organisations/vat/check-vat-number/lookup/" & VATNumber

            response = http.QuickGetStr(url)

            If http.LastMethodSuccess <> True Then
                Console.WriteLine("Fehler: " & http.LastErrorText)
                Return False
            End If

            ' Antwort ausgeben
            Console.WriteLine("API Antwort: " & response)
            Return True
        End If
        Return False
    End Function

    Public Class RefreshTokenResultJSON
        Public Property access_token As String
    End Class
End Class

'Public Class Startup
'    Public Sub New(ByVal configuration As IConfiguration)
'        configuration = configuration
'    End Sub

'    Public ReadOnly Property Configuration As IConfiguration

'    Public Sub ConfigureServices(ByVal services As IServiceCollection)
'        services.Configure(Configuration)

'        services.Configure(Of CookiePolicyOptions)(Function(options)
'                                                       options.CheckConsentNeeded = Function(context) True
'                                                       options.MinimumSameSitePolicy = SameSiteMode.None
'                                                   End Function)
'        services.AddSession(Function(options)
'                                options.IdleTimeout = TimeSpan.FromSeconds(10)
'                                options.Cookie.HttpOnly = True
'                                options.Cookie.IsEssential = True
'                            End Function)
'        services.AddAuthentication(Function(options)
'                                       options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme
'                                       options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
'                                       options.DefaultChallengeScheme = "HMRC"
'                                   End Function).AddCookie().AddOAuth("HMRC", Function(options)
'                                                                                  options.ClientId = Configuration("clientId")
'                                                                                  options.ClientSecret = Configuration("clientSecret")
'                                                                                  options.CallbackPath = New PathString(Configuration("oauthCallbackUri"))
'                                                                                  options.Scope.Add("hello")
'                                                                                  options.SaveTokens = True
'                                                                                  options.AuthorizationEndpoint = Configuration("uri") & "/oauth/authorize"
'                                                                                  options.TokenEndpoint = Configuration("uri") & "/oauth/token"
'                                                                              End Function)
'        services.AddRazorPages(Function(options)
'                                   options.Conventions.AddPageRoute("/HelloWorld/Index", "")
'                               End Function)
'    End Sub

'    Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
'        If env.IsDevelopment() Then
'            app.UseDeveloperExceptionPage()
'        Else
'            app.UseExceptionHandler("/Error")
'            app.UseHsts()
'        End If

'        app.UseHttpsRedirection()
'        app.UseStaticFiles()
'        app.UseRouting()
'        app.UseAuthorization()
'        app.UseAuthentication()
'        app.UseSession()
'        app.UseCookiePolicy()
'        app.UseEndpoints(Function(endpoints)
'                             endpoints.MapRazorPages()
'                             endpoints.MapControllerRoute(name:="default", pattern:="{controller=HelloWorld}/{action=Index}")
'                         End Function)
'    End Sub
'End Class



Public Class VATResponse
    Public Class Address
        Public Property line1 As String
        Public Property postcode As String
        Public Property countryCode As String
    End Class

    Public Class Target
        Public Property name As String
        Public Property vatNumber As String
        Public Property address As Address
    End Class

    Public Class Root
        Public Property target As Target
        Public Property processingDate As DateTime
    End Class

End Class
