Imports DigitalData.Modules.Logging

Public Class frmConfigService
    Private _Logger As Logger
    Private _Service As ClassService
    Private _ErrorHandler As ClassErrorHandler

    Private Sub frmServiceConfig_Load(sender As Object, e As EventArgs) Handles Me.Load
        _Logger = My.LogConfig.GetLogger()
        _Service = New ClassService(My.LogConfig)
        _ErrorHandler = New ClassErrorHandler(_Logger)

        If My.SystemConfigManager.Config.ServiceConnection <> String.Empty Then
            txtIPAddress.Text = My.SystemConfigManager.Config.ServiceIP
            txtPort.Text = My.SystemConfigManager.Config.ServicePort
        End If

        txtIPAddress.Focus()
    End Sub

    Private Async Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
        Try
            Dim oIPAddress = txtIPAddress.Text
            Dim oPort = txtPort.Text
            Dim oEndpointURL = $"net.tcp://{oIPAddress}:{oPort}/DigitalData/Services/Main"
            Dim oResult As ClassService.ConnectionTestResult

            My.SysConfig.ServiceIP = oIPAddress
            My.SysConfig.ServicePort = Integer.Parse(oPort)

            lblStatus.Text = "Verbindung wird hergestellt..."
            oResult = Await _Service.TestConnectionAsync()

            If oResult = ClassService.ConnectionTestResult.Successful Then
                My.SystemConfigManager.Save()
                lblStatus.Text = "Verbindung hergestellt."
            Else
                Select Case oResult
                    Case ClassService.ConnectionTestResult.NotFound
                        lblStatus.Text = "Dienst konnte nicht gefunden werden. Bitte überprüfen sie Addresse und Port."
                    Case ClassService.ConnectionTestResult.EmptyURI
                        lblStatus.Text = "Bitte tragen Sie eine gültige Dienst Adresse ein."
                    Case ClassService.ConnectionTestResult.Authentication
                        lblStatus.Text = "Authentifizierungsfehler. Prüfen Sie, ob sich Ihr Gerät in der korrekten Domäne befindet."
                    Case Else
                        lblStatus.Text = "Unbekannter Fehler."
                End Select
            End If
        Catch ex As Exception
            _ErrorHandler.ShowErrorMessage(ex)
        End Try
    End Sub

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        If My.SystemConfigManager.Config.ServiceConnection <> String.Empty Then
            DialogResult = DialogResult.OK
            Close()
        Else
            MsgBox("Bitte tragen Sie die Dienst Adresse ein!")
        End If
    End Sub
End Class