Imports System.IO
Imports DigitalData.Modules.Interfaces
Imports DigitalData.Modules.Jobs
Imports DigitalData.Modules.Logging

Public Class GraphQLJob
    Inherits JobBase
    Implements IJob(Of GraphQLArgs)

    Public Sub New(LogConfig As LogConfig)
        MyBase.New(LogConfig, Nothing, Nothing)
    End Sub

    Public Sub Start(Args As GraphQLArgs) Implements IJob(Of GraphQLArgs).Start
        Dim oInterface As New GraphQLInterface(
            _LogConfig, Args.BaseUrl, Args.Email, Args.Password, Args.CertificateFile, Args.CertificatePassword)

        Dim oQuery = "query Nls{
            niederlassungen(offset: 0, limit: 5) {
                niederlassungen {
                    mdnr
                    bezeichnung
                    sparte {
                        id
                        name
                        __typename
                    }
                    __typename
                }
                __typename
            }
        }"

        _Logger.Info("Logging in..")

        ' Login to get cookie
        Dim oLoginResponse = oInterface.Login()

        ' save cookie for future requests
        oInterface.SaveCookies(oLoginResponse.Cookies.Item(0))

        _Logger.Info("Getting the data..")

        ' get the data
        Dim oDataResponse = oInterface.GetData(oQuery, "Nls")
        Dim oResult As String

        ' write data to string
        Using oStream = oDataResponse.GetResponseStream()
            Using oReader As New StreamReader(oStream)
                oResult = oReader.ReadToEnd()
            End Using
        End Using

        ' TODO: save data to file
        _Logger.Info("Response is:")
        _Logger.Info(oResult)

        _Logger.Info("Logging out..")

        ' logout
        Dim oLogoutResponse = oInterface.Logout()
    End Sub

    Public Function ShouldStart(Arguments As GraphQLArgs) As Boolean Implements IJob(Of GraphQLArgs).ShouldStart
        Return Arguments.Enabled
    End Function
End Class
