Imports System.ComponentModel
Imports System.Data.SqlClient
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Encryption
Imports DigitalData.Modules.Filesystem
Imports DigitalData.Modules.Logging

Public Class frmSQLConfig
    Private Const STRING_CONNECTION_SUCCESSFUL = "Die Verbindung wurde erfolgreich aufgebaut!" & vbNewLine & "Möchten Sie diese Verbindung nun in der Anwendung speichern?"

    Private ReadOnly Logger As Logger
    Private ReadOnly LogConfig As LogConfig

    Public Property ConnectionString As String = String.Empty
    Public Property FormTitle As String = ""

    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
    End Sub

    Public Sub New(LogConfig As LogConfig)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Me.LogConfig = LogConfig
        Logger = LogConfig.GetLogger()
    End Sub

    Private Sub frmSQLConfig_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim oConnectionString = ConnectionString

        If FormTitle.Count > 0 Then
            Text = $"{FormTitle} - {Text}"
        End If

        If Not oConnectionString = String.Empty Then
            Dim oBuilder As SqlConnectionStringBuilder
            Try
                oBuilder = New SqlConnectionStringBuilder(ConnectionString)
            Catch ex As Exception
                oBuilder = Nothing
            End Try

            If oBuilder Is Nothing Then
                MsgBox("Connection String ist ungültig!", MsgBoxStyle.Critical, Text)
                Exit Sub
            End If

            If oConnectionString.Contains("Trusted") Then
                chkWinAuth.Checked = True
                txtConnectionString.Text = oConnectionString
            Else
                chkWinAuth.Checked = False
                txtConnectionString.Text = oConnectionString.Replace(oBuilder.Password, "XXXXXX")
                txtUserName.Text = oBuilder.UserID
            End If

            txtServerName.Text = oBuilder.DataSource
            cmbDatabase.Text = oBuilder.InitialCatalog
        End If
    End Sub

    Private Sub chkWinAuth_CheckedChanged(sender As Object, e As EventArgs) Handles chkWinAuth.CheckedChanged
        txtPassword.Enabled = Not chkWinAuth.Checked
        txtUserName.Enabled = Not chkWinAuth.Checked
    End Sub

    Private Sub cmbDatabase_Click(sender As Object, e As EventArgs) Handles cmbDatabase.Click
        Cursor = Cursors.WaitCursor

        Dim oConnectionString As String = GetConnectionString(False)
        Dim oDatabase As New MSSQLServer(LogConfig, oConnectionString)

        If oDatabase.DBInitialized = False Then
            MsgBox("Verbindung fehlgeschlagen!", MsgBoxStyle.Critical, Text)
            Exit Sub
        End If

        Try
            Using oConnection = New SqlClient.SqlConnection(oConnectionString)
                oConnection.Open()
                Using oCommand As New SqlClient.SqlCommand("sp_databases", oConnection)
                    Using oReader As SqlClient.SqlDataReader = oCommand.ExecuteReader
                        If oReader.HasRows Then
                            cmbDatabase.Properties.Items.Clear()

                            Do While oReader.Read
                                cmbDatabase.Properties.Items.Add(oReader("Database_Name"))
                            Loop
                            cmbDatabase.ShowPopup()
                        Else
                            MsgBox("The standard-databases could not be retrieved. The default database will be set!" & vbNewLine & "Check rights in sql-server for user: " & Me.txtUserName.Text, MsgBoxStyle.Exclamation)
                        End If
                    End Using
                End Using
            End Using

        Catch ex As Exception
            Logger.Error(ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Function GetConnectionString(WithDatabase As Boolean) As String
        Dim oConnectionString As String

        If chkWinAuth.Checked Then
            oConnectionString = $"Data Source={txtServerName.Text};Trusted_Connection=True;"
        Else
            oConnectionString = $"Server={txtServerName.Text};User Id={txtUserName.Text};Password={txtPassword.Text};"
        End If

        If WithDatabase Then
            oConnectionString &= $"Database={cmbDatabase.Text};"
        End If

        Return oConnectionString
    End Function

    Private Sub btnTestConnection_Click(sender As Object, e As EventArgs) Handles btnTestConnection.Click
        Try
            Dim oConnectionString = GetConnectionString(True)

            Using oConnection As New SqlConnection(oConnectionString)
                oConnection.Open()
                oConnection.Close()
            End Using

            Dim oResult = MessageBox.Show(STRING_CONNECTION_SUCCESSFUL, Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)

            If oResult = DialogResult.Yes Then
                Dim oPlainTextConnectionString = $"Server={txtServerName.Text};Database={cmbDatabase.Text};User Id={txtUserName.Text};Password={txtPassword.Text};"
                ConnectionString = MSSQLServer.EncryptConnectionString(oPlainTextConnectionString)
                Close()
            End If
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Error while connecting to Database", MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub frmSQLConfig_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If ConnectionString <> String.Empty Then
            DialogResult = DialogResult.OK
        Else
            DialogResult = DialogResult.Cancel
        End If
    End Sub
End Class