Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.Logging

Public Class frmServiceConfig
    Private Client As Client
    Private Logger As Logger

    Private Sub frmServiceConfig_Load(sender As Object, e As EventArgs) Handles Me.Load
        Logger = My.LogConfig.GetLogger()

        If My.SystemConfig.AppServerConfig <> String.Empty Then
            Dim oAddress = Client.ParseServiceAddress(My.SystemConfig.AppServerConfig)
            txtServiceAddress.Text = oAddress.Item1
            txtServicePort.Text = oAddress.Item2
        End If

        txtServiceAddress.Focus()
    End Sub

    Private Sub btnOK_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOK.ItemClick
        Try
            Dim oIPAddress = txtServiceAddress.Text
            Dim oPort = Integer.Parse(txtServicePort.Text)
            Dim oEndpointURL = $"net.tcp://{oIPAddress}:{oPort}/DigitalData/Services/Main"

            Client = New Client(My.LogConfig, oIPAddress, oPort)

            lblStatus.Text = "Verbindung wird hergestellt..."
            Dim oResult = Client.Connect()

            If oResult = True Then
                My.SystemConfig.AppServerConfig = $"{oIPAddress}:{oPort.ToString}"
                My.SystemConfigManager.Save()
                lblStatus.Text = "Verbindung hergestellt."
            Else
                lblStatus.Text = "Verbindung fehlgeschlagen."
                ' TODO: Make a connection test that is as elaborate as this one  :D
                '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

            DialogResult = DialogResult.OK
            Close()
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Fehler beim Verbindungsaufbau", MsgBoxStyle.Critical, Text)
        End Try
    End Sub


End Class