Imports DD_LIB_Standards
Imports DD_Clipboard_Watcher.ClassHotkey.ModfierKey

Public Class frmConfig_Basic
    Dim WithEvents Hotkey As New ClassHotkey(Me)

    Private Sub BtnConnect_Click(sender As Object, e As EventArgs) Handles BtnConnect.Click
        Try
            Dim con As String
            If chkbxUserAut.Checked Then
                con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.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)
            'während Verbindungsaufbau Sanduhr-Mauszeiger
            Cursor = Cursors.WaitCursor
            connection.Open()
            Cursor = Cursors.Default
            'DialogResult = Windows.Forms.DialogResult.OK
            Dim result As MsgBoxResult
            Dim msg = "Die Verbindung wurde erfolgreich aufgebaut!" & vbNewLine & "Möchten Sie diese Verbindung nun in der Anwendung speichern?"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Connection was successfully opened!" & vbNewLine & "Would You like to save it?"
            End If
            result = MessageBox.Show(msg, "Database-Connection", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                CONNECTION_CHANGED = True
                'Set the construction string
                MyConnectionString = con 'csb.ConnectionString
                clsDatabase.Init(MyConnectionString)
                If chkbxUserAut.Checked = False Then
                    Dim wrapper As New clsEncryption("!35452didalog=")
                    Dim cipherText As String = wrapper.EncryptData(Me.txtPasswort.Text)
                    Dim pw As String = cipherText
                    con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & pw & ";"
                End If

                'SaveConfigValue("MyConnectionString", con)
                ConfigManager.Config.ConnectionString = con
                ConfigManager.Save()

                Dim csb As New SqlClient.SqlConnectionStringBuilder
                csb.ConnectionString = MyConnectionString
                Dim constr = connection.ConnectionString
                If chkbxUserAut.Checked = False Then
                    constr = constr.Replace(csb.Password, "XXXXX")
                End If
                txtActualConnection.Text = constr
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MsgBox("Error in Connectionbuild: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub cmbDatenbank_MouseClick(sender As Object, e As MouseEventArgs) Handles cmbDatenbank.MouseClick
        Load_Databases()
    End Sub
    Sub Load_Databases()
        Try
            Cursor = Cursors.WaitCursor
            Dim csb As New SqlClient.SqlConnectionStringBuilder With {
                .DataSource = txtServer.Text,
                .IntegratedSecurity = False,
                .UserID = txtUser.Text,
                .Password = txtPasswort.Text
            }

            Dim con As String
            If chkbxUserAut.Checked Then
                con = $"Data Source={txtServer.Text};Trusted_Connection=True;"
            Else
                con = $"Server={txtServer.Text};User Id={txtUser.Text};Password={txtPasswort.Text};"
            End If
            Dim connection As New SqlClient.SqlConnection(con)
            connection.Open()
            Dim cmd As New SqlClient.SqlCommand("sp_databases", connection)
            cmd.CommandType = CommandType.StoredProcedure
            Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader
            If dr.HasRows Then
                cmbDatenbank.Items.Clear()
                Do While dr.Read
                    cmbDatenbank.Items.Add(dr("Database_Name"))
                Loop
                cmbDatenbank.DroppedDown = True
            Else
                MsgBox("The standard-databases could not be retrieved. The default database will be set!" & vbNewLine & "Check rights in sql-server for user: " & Me.txtUser.Text, MsgBoxStyle.Exclamation)
            End If
            connection.Close()
        Catch ex As Exception
            If ex.Message.ToLower.Contains("he standard-databases") Or ex.Message.ToLower.Contains("ie standard-datenbanken") Then
                cmbDatenbank.Text = "DD_ECM"
            End If
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Load Databases:")
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub frmConfig_Basic_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lblChanges.Visible = False
        If Not MyConnectionString = String.Empty Then
            CONNECTION_CHANGED = False
            Try
                Dim csb As New SqlClient.SqlConnectionStringBuilder
                csb.ConnectionString = MyConnectionString

                Dim constr = MyConnectionString
                If Not MyConnectionString.Contains("Trusted") Then
                    constr = constr.Replace(csb.Password, "XXXXX")
                    txtUser.Text = csb.UserID
                    chkbxUserAut.Checked = False
                Else
                    chkbxUserAut.Checked = True
                End If

                Try
                    txtServer.Text = csb.DataSource
                    cmbDatenbank.Text = csb.InitialCatalog
                Catch ex As Exception

                End Try

                txtActualConnection.Text = constr
                chkLogErrorsOnly.Checked = LogErrorsOnly
            Catch ex As Exception
                MsgBox("Fehler in FormLoad: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        LinkLabel1.LinkVisited = True
        Process.Start("http://www.didalog.de/Support")
    End Sub

    Private Sub btnApplicationFolder_Click(sender As Object, e As EventArgs) Handles btnApplicationFolder.Click
        Process.Start(Application.UserAppDataPath())
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Process.Start(LogConfig.LogDirectory)
    End Sub

    Private Sub chkLogErrorsOnly_CheckedChanged(sender As Object, e As EventArgs) Handles chkLogErrorsOnly.CheckedChanged
        LogErrorsOnly = chkLogErrorsOnly.Checked
        LogConfig.Debug = Not LogErrorsOnly

        ConfigManager.Config.LogErrorsOnly = LogErrorsOnly
        ConfigManager.Save()
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Select Case TabControl1.SelectedIndex
            Case 1
                Try
                    cmbfunctionHit.SelectedIndex = cmbfunctionHit.FindStringExact(HotkeyFunctionKey)
                    txtHotkeySearchKey.Text = HotkeySearchKey
                Catch ex As Exception

                End Try
            Case 2
                LabelVersion.Text = $"Version: {My.Application.Info.Version.ToString}"
        End Select
    End Sub

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

    Private Sub btnChangeHotkey_Click(sender As Object, e As EventArgs) Handles btnChangeHotkey.Click
        Try
            If cmbfunctionHit.SelectedIndex <> -1 Then
                Hotkey.RemoveHotKey(ClassConstants.HOTKEY_TRIGGER_WATCHER)

                ConfigManager.Config.HotkeyFunctionKey = cmbfunctionHit.Text
                ConfigManager.Config.HotkeySearchKey = txtHotkeySearchKey.Text
                ConfigManager.Save()

                Dim keyCode As Keys
                Dim kc As New KeysConverter
                Dim obj As Object = kc.ConvertFromString(txtHotkeySearchKey.Text.ToUpper)
                keyCode = CType(obj, Keys)
                If cmbfunctionHit.Text = ClassConstants.HOTKEY_CTRL Then
                    Hotkey.AddHotKey(keyCode, MOD_CONTROL, ClassConstants.HOTKEY_TRIGGER_WATCHER)
                ElseIf cmbfunctionHit.Text = "SHIFT" Then
                    Hotkey.AddHotKey(keyCode, MOD_SHIFT, ClassConstants.HOTKEY_TRIGGER_WATCHER)
                End If

                Dim msg = "Die Änderung des Hotkeys war erfolgreich." & vbNewLine & "Da es sich um einen global Hotkey handelt muss die Anwendung neugestartet werden!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "The change of your desired hotkey was successfull." & vbNewLine & "For using it the application must be restarted now!"
                End If
                MsgBox(msg, MsgBoxStyle.Information)
                Cursor = Cursors.WaitCursor
                Application.Restart()
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in ChangeHotkey:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, Text)
        End Try
    End Sub
End Class