Imports System.Globalization
Imports System.IO
Imports DigitalData.Modules.Database

Public Class frmKonfig
    Private email As New ClassEmail
    Dim formshown As Boolean = False

    Private Sub frmKonfig_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Try
            ' Initialize Log Grid
            GridControlLogs.DataSource = LOGCONFIG.Logs
            GridControlLogs.ForceInitialize()
            gvLogs.Columns.First().Caption = "Log Nachricht"


            If CONNECTION_STRING_ECM = String.Empty Then
                Me.TabControl1.SelectedIndex = 1
                Load_ConString("")
            Else
                Load_ConString(CONNECTION_STRING_ECM)
                Me.TBPM_KONFIGURATIONTableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
                Me.TBPM_KONFIGURATIONTableAdapter.Fill(Me.DD_DMSLiteDataSet.TBPM_KONFIGURATION)
            End If

            chkLogErrorsOnly.Checked = CBool(DEBUG)
            txtIntervall.Text = CONFIG.Config.ReminderTimer

        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Formload Grundkonfig:")
        End Try
    End Sub


    Private Sub cmbDatenbank_Click(sender As System.Object, e As System.EventArgs) Handles cmbDatenbank.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim csb As New SqlClient.SqlConnectionStringBuilder
            csb.DataSource = Me.txtServer.Text
            csb.IntegratedSecurity = False
            csb.UserID = Me.txtUser.Text
            csb.Password = Me.txtPasswort.Text

            Dim con As String
            If chkbxUserAut.Checked Then
                con = "Data Source=" & Me.txtServer.Text & ";Trusted_Connection=True;"
            Else
                con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";"
            End If
            Dim connection As New SqlClient.SqlConnection(con) 'csb.ConnectionString)
            connection.Open()
            Dim cmd As New SqlClient.SqlCommand("sp_databases", connection) With {
                .CommandType = CommandType.StoredProcedure
            }
            ' Ausführen und Ergebnis in einer ListBox anzeigen
            Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader
            If dr.HasRows Then
                Do While dr.Read
                    cmbDatenbank.Items.Add(dr("Database_Name"))
                Loop
                cmbDatenbank.DroppedDown = True
            End If
            connection.Close()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Datenbank-Connect:")
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub BtnConnect_Click(sender As System.Object, e As System.EventArgs) Handles BtnConnect.Click
        Try
            Dim oPlainConnectionString, oEncryptedConnectionString As String
            If chkbxUserAut.Checked Then
                oPlainConnectionString = "Data Source=" & Me.txtServer.Text & ";Initial Catalog=" & Me.cmbDatenbank.Text & ";Trusted_Connection=True;"
            Else
                oPlainConnectionString = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";"
            End If

            Dim connection As New SqlClient.SqlConnection(oPlainConnectionString) 'csb.ConnectionString)
            'während Verbindungsaufbau Sanduhr-Mauszeiger
            Cursor = Cursors.WaitCursor
            connection.Open()
            Cursor = Cursors.Default
            'DialogResult = Windows.Forms.DialogResult.OK
            Dim result As MsgBoxResult
            result = MessageBox.Show("Die Verbindung wurde erfolgreich aufgebaut!" & vbNewLine & "Möchten Sie diese Verbindung nun in der Anwendung speichern?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                'ConnectionString in Anwendung speichern
                CONNECTION_STRING_ECM = oPlainConnectionString

                'Das Passwort verschlüsseln
                If chkbxUserAut.Checked = False Then
                    Dim wrapper As New ClassEncryption("!35452didalog=")
                    Dim cipherText As String = wrapper.EncryptData(Me.txtPasswort.Text)
                    Dim pw As String = cipherText
                    oEncryptedConnectionString = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & pw & ";"
                Else
                    oEncryptedConnectionString = oPlainConnectionString
                End If

                If RadioDefaultConnection.Checked Then
                    LOGGER.Debug("ConnectionString saved")
                    CONNECTION_STRING_ECM = oPlainConnectionString
                    CONFIG.Config.ConnectionString = oEncryptedConnectionString
                    CONFIG.Save(ForceAll:=True)
                Else
                    LOGGER.Debug("ConnectionStringTest saved")
                    CONNECTION_STRING_ECM = oPlainConnectionString
                    CONFIG.Config.ConnectionStringTest = oEncryptedConnectionString
                    CONFIG.Save(ForceAll:=True)
                End If

                Load_ConString(CONNECTION_STRING_ECM)
                Me.TBPM_KONFIGURATIONTableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
                Me.TBPM_KONFIGURATIONTableAdapter.Fill(Me.DD_DMSLiteDataSet.TBPM_KONFIGURATION)
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            Cursor = Cursors.Default
            MsgBox("Fehler beim Verbindungsaufbau: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub frmKonfig_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        formshown = True

    End Sub
    Private Sub chkbxUserAut_CheckedChanged(sender As Object, e As EventArgs) Handles chkbxUserAut.CheckedChanged
        If chkbxUserAut.Checked Then
            Me.txtPasswort.Enabled = False
            Me.txtUser.Enabled = False
        Else
            Me.txtPasswort.Enabled = True
            Me.txtUser.Enabled = True
        End If
    End Sub



    Private Sub TBPM_KONFIGURATIONBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBPM_KONFIGURATIONBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DD_DMSLiteDataSet)
    End Sub

    Private Sub Button1_Click_3(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox("Culture-Name: " & CultureInfo.CurrentCulture.Name & vbNewLine & "Culture-ThreeLetterISOLanguageName: " & CultureInfo.CurrentCulture.ThreeLetterISOLanguageName & vbNewLine &
               "CurrentUICulture-Name: " & CultureInfo.CurrentUICulture.Name & vbNewLine & "CurrentUICulture-ThreeLetterISOLanguageName: " & CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName)
    End Sub
    Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs)
        My.Settings.Save()
    End Sub
    Sub Load_ConString(constr As String)
        txtActualConnection.Text = MaskConnectionStringPassword(constr)
    End Sub

    Private Function MaskConnectionStringPassword(ConnectionString As String) As String
        If ConnectionString.Contains("Password=") Then
            Dim oBuilder As New SqlClient.SqlConnectionStringBuilder() With {
                .ConnectionString = ConnectionString
            }
            Return ConnectionString.Replace(oBuilder.Password, "XXXXXX")
        End If

        Return ConnectionString
    End Function

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        ' Specify that the link was visited.
        Me.LinkLabel1.LinkVisited = True
        Try
            Using connection As New SqlClient.SqlConnection(CONNECTION_STRING_ECM)
                connection.Open()

                Dim oSql As String = "SELECT CAT_STRING FROM TBDD_CATALOG WHERE CAT_TITLE = 'DDSUPPORT_PORTAL'"
                Dim oCmd As New SqlClient.SqlCommand(oSql, connection)
                Dim oSupportLinkObj As Object = oCmd.ExecuteScalar
                Dim oSupportLink As String = If(oSupportLinkObj IsNot Nothing, oSupportLinkObj.ToString, "")

                If Not String.IsNullOrEmpty(oSupportLink) Then
                    Process.Start(oSupportLink)
                Else
                    MsgBox("Support-Link nicht gefunden.", MsgBoxStyle.Information)
                End If

            End Using
        Catch ex As Exception
            MsgBox("Fehler beim Öffnen des Support-Links: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnOpenAppDataFolder.Click
        Process.Start(USER_CONFIG_DIRECTORY)
    End Sub

    Private Sub btnopenlog_Click(sender As Object, e As EventArgs) Handles btnOpenLogFolder.Click
        Try
            Process.Start(LOGCONFIG.LogDirectory)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub txtIntervall_TextChanged(sender As Object, e As EventArgs) Handles txtIntervall.TextChanged
        Try
            CONFIG.Config.ReminderTimer = CInt(txtIntervall.Text)
            CONFIG.Save()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub chkLogErrorsOnly_CheckedChanged(sender As Object, e As EventArgs) Handles chkLogErrorsOnly.CheckedChanged
        DEBUG = chkLogErrorsOnly.Checked
        LOGCONFIG.Debug = DEBUG
        CONFIG.Config.DEBUG = DEBUG
        CONFIG.Save()
        'SaveMySettingsValue("LogErrorsOnly", chkLogErrorsOnly.Checked)
    End Sub

    Private Sub RadioDefaultConnection_CheckedChanged(sender As Object, e As EventArgs) Handles RadioDefaultConnection.CheckedChanged
        txtActualConnection.Text = MaskConnectionStringPassword(CONFIG.Config.ConnectionString)


    End Sub

    Private Sub RadioAlternativeConnection_CheckedChanged(sender As Object, e As EventArgs) Handles RadioAlternativeConnection.CheckedChanged
        txtActualConnection.Text = MaskConnectionStringPassword(CONFIG.Config.ConnectionStringTest)
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim di As New IO.DirectoryInfo(USER_CONFIG_DIRECTORY)
        Dim diar1 As IO.FileInfo() = di.GetFiles()
        Dim dra As IO.FileInfo

        'list the names of all files in the specified directory
        For Each dra In diar1
            If dra.Name <> "UserConfig.xml" Then
                Try
                    System.IO.File.Delete(dra.FullName)
                    LOGGER.Info($"ConfigFile {dra.FullName} has been deleted!")
                Catch ex As Exception

                End Try

            End If

        Next
        MsgBox("The UserConfiguration has been set back to default!", MsgBoxStyle.OkOnly)

    End Sub

    Private Sub LogNachrichtenLeerenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogNachrichtenLeerenToolStripMenuItem.Click
        LOGCONFIG.ClearLogs()
        GridControlLogs.DataSource = LOGCONFIG.Logs
    End Sub

    Private Sub SpeichereLogAlsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SpeichereLogAlsToolStripMenuItem.Click
        Try
            SaveFileDialog1.Filter = "Text File|*.txt"
            If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
                GridControlLogs.ExportToText(SaveFileDialog1.FileName)
            End If
        Catch ex As Exception
            MsgBox("Error in Export: " & ex.Message)
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            If TabControl1.SelectedIndex = 1 Then
                If IsDirectoryAccessible(LOGCONFIG.LogDirectory) Then
                    btnOpenLogFolder.Enabled = True
                Else
                    LOGGER.Info("Logpath is not accessible")
                    btnOpenLogFolder.Enabled = False
                End If
                If IsDirectoryAccessible(USER_CONFIG_DIRECTORY) Then
                    btnOpenAppDataFolder.Enabled = True
                Else
                    LOGGER.Info("Appdata-Path is not accessible")
                    btnOpenAppDataFolder.Enabled = False
                End If


            End If
        Catch ex As Exception

        End Try
    End Sub
    Function IsDirectoryAccessible(pDirectoryPath As String) As Boolean
        Try
            ' Prüfen, ob das Verzeichnis existiert
            If Not Directory.Exists(pDirectoryPath) Then
                Return False
            End If

            ' Versuch, das Verzeichnis zu öffnen und seine Dateien aufzulisten
            Dim files As String() = Directory.GetFiles(pDirectoryPath)
            Return True
        Catch ex As UnauthorizedAccessException
            ' Zugriff verweigert
            Return False
        Catch ex As IOException
            ' Ein allgemeiner E/A-Fehler
            Return False
        Catch ex As Exception
            ' Ein anderer Fehler
            Return False
        End Try
    End Function

    Private Sub BtnCreateLogfiles_Click(sender As Object, e As EventArgs) Handles BtnCreateLogfiles.Click
        ClassAllgemeineFunktionen.Save_Logfiles()


    End Sub
End Class