Imports System.Threading
Imports System.Globalization

Public Class frmConfig_Basic
    Dim formloaded As Boolean = False
    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
            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
                CONNECTION_CHANGED = True
                'Set the construction string
                MyConnectionString = con 'csb.ConnectionString
                My.Settings.Save()
                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
                    con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & pw & ";"
                End If
                SaveMySettingsValue("MyConnectionString", con, "ConfigMain")
                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
                Me.txtActualConnection.Text = constr
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MsgBox("Fehler beim Verbindungsaufbau: " & 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
            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 & ";"
                con = "Server=" & Me.txtServer.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)
            cmd.CommandType = CommandType.StoredProcedure
            ' Ausführen und Ergebnis in einer ListBox anzeigen
            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. 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_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        SaveMySettingsValue("WDResultListCount", txtwdSearch_Count.Text, "ConfigMain")
    End Sub

    Private Sub frmConfig_Basic_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        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

                Me.txtActualConnection.Text = constr
                chkbxloadWDDocs.Checked = Sett_LoadWD_Docs
                chkLogErrorsOnly.Checked = LogErrorsOnly
                txtwdSearch_Count.Text = WDResultListCount
                chkboxQuickMenue.Checked = Sett_ShowQuickMenue
                CheckBoxWD_ShowEnitityDocs.Checked = WD_ShowEnitityDocs
                Dim sql As String = "SELECT 0,'' UNION ALL SELECT T.GUID, T.FORM_TITLE FROM TBPMO_FORM_CONSTRUCTOR T"
                Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "ConstructorForms - from Config")
                If DT.Rows.Count > 0 Then
                    cmbConstructor.Enabled = True
                    cmbConstructor.DataSource = DT
                    cmbConstructor.DisplayMember = DT.Columns(1).ColumnName
                    cmbConstructor.ValueMember = DT.Columns(0).ColumnName
                    If Sett_ConstructorStart <> 0 Then
                        cmbConstructor.SelectedValue = Sett_ConstructorStart
                    End If

                Else
                    cmbConstructor.Enabled = False
                End If
            Catch ex As Exception
                MsgBox("Fehler in FormLoad: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try



        End If
    End Sub

    Private Sub chkbxloadWDDocs_CheckedChanged(sender As Object, e As EventArgs) Handles chkbxloadWDDocs.CheckedChanged
        Sett_LoadWD_Docs = chkbxloadWDDocs.Checked
        SaveMySettingsValue("Sett_LoadWD_Docs", Sett_LoadWD_Docs, "ConfigMain")
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        ' Specify that the link was visited.
        Me.LinkLabel1.LinkVisited = True
        ' Navigate to a URL.
        System.Diagnostics.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(ClassLogger.DateiSpeicherort)
    End Sub

    Private Sub chkLogErrorsOnly_CheckedChanged(sender As Object, e As EventArgs) Handles chkLogErrorsOnly.CheckedChanged
        LogErrorsOnly = chkLogErrorsOnly.Checked
        SaveMySettingsValue("LogErrorsOnly", LogErrorsOnly, "ConfigMain")
    End Sub

    Private Sub chkboxQuickMenue_CheckedChanged(sender As Object, e As EventArgs) Handles chkboxQuickMenue.CheckedChanged
        Sett_ShowQuickMenue = chkboxQuickMenue.Checked
        SaveMySettingsValue("Sett_ShowQuickMenue", Sett_ShowQuickMenue, "ConfigMain")
    End Sub

    Private Sub CheckBoxWD_ShowEnitityDocs_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBoxWD_ShowEnitityDocs.CheckedChanged
        WD_ShowEnitityDocs = CheckBoxWD_ShowEnitityDocs.Checked
        SaveMySettingsValue("WD_ShowEnitityDocs", WD_ShowEnitityDocs, "ConfigMain")
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        My.Settings.Save()
    End Sub

    Private Sub cmbConstructor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbConstructor.SelectedIndexChanged
        If cmbConstructor.SelectedIndex <> -1 And formloaded = True Then
            If Sett_ConstructorStart <> cmbConstructor.SelectedValue Then
                Sett_ConstructorStart = cmbConstructor.SelectedValue
                SaveMySettingsValue("Sett_ConstructorStart", Sett_ConstructorStart, "ConfigMain")
            End If

        End If
    End Sub

    Private Sub frmConfig_Basic_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        formloaded = True
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Select Case TabControl1.SelectedIndex
            Case 1
                cmbLanguage.SelectedIndex = cmbLanguage.FindStringExact(USER_LANGUAGE)
            Case 2
                Dim SCAN_folderwatch = ClassDatabase.Execute_Scalar("SELECT FOLDER_PATH FROM TBPMO_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'SCAN' AND USER_ID = " & USER_GUID, True)
                If Not SCAN_folderwatch Is Nothing Then
                    CURRENT_SCAN_FOLDERWATCH = SCAN_folderwatch
                End If
                Me.txtScanFolderWatch.Text = CURRENT_SCAN_FOLDERWATCH

                If Not ClassFolderWatcher.FolderWatcher_SCAN Is Nothing Then
                    If ClassFolderWatcher.FolderWatcher_SCAN.EnableRaisingEvents = True Then
                        'If USER_LANGUAGE = "de-DE" Then
                        btnstartstop2.Text = "Überwachung stoppen"
                        'Else
                        '    btnstartstop2.Text = "Stop hotfolder"
                        'End If

                        btnstartstop2.Image = My.Resources.bell_delete
                    Else
                        ' If USER_LANGUAGE = "de-DE" Then
                        btnstartstop2.Text = "Überwachung starten"
                        'Else
                        'btnstartstop2.Text = "Stop hotfolder"
                        'End If

                        btnstartstop2.Image = My.Resources.bell_go
                    End If
                Else
                    ' If USER_LANGUAGE = "de-DE" Then
                    btnstartstop2.Text = "Überwachung starten"
                    'Else
                    '   btnstartstop2.Text = "Stop hotfolder"
                    'End If

                    btnstartstop2.Image = My.Resources.bell_go
                End If
                Me.DataGridView1.DataSource = DTEXCLUDE_FILES

        End Select
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim fbdialog As New FolderBrowserDialog
        If fbdialog.ShowDialog() = DialogResult.OK Then
            CheckScanFolder(fbdialog.SelectedPath)
        End If
    End Sub
    Sub CheckScanFolder(mypath As String)
        Try
            Try
                If (Not System.IO.Directory.Exists(mypath)) Then
                    System.IO.Directory.CreateDirectory(mypath)
                End If
            Catch ex As Exception
                ClassLogger.Add(" >> Fehler beim Erstellen des Folderwatchordners: " & mypath, False)
                ClassLogger.Add(" >> " & ex.Message, False)

                MsgBox("Error in creating Hotfolder: " & mypath & vbNewLine & "Please check the rights!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)


                Exit Sub
            End Try

            Dim folderwatch = ClassDatabase.Execute_Scalar("SELECT GUID FROM TBPMO_FOLDERWATCH_USER WHERE USER_ID = " & USER_GUID & " AND FOLDER_TYPE = 'SCAN'", True)
            Dim sql As String
            If folderwatch Is Nothing Then
                sql = "INSERT INTO TBPMO_FOLDERWATCH_USER (USER_ID, FOLDER_PATH, FOLDER_TYPE, ADDED_WHO) VALUES (" & USER_GUID & ",'" & mypath & "','SCAN','" & Environment.UserName & "')"
            Else
                sql = "UPDATE TBPMO_FOLDERWATCH_USER SET FOLDER_PATH = '" & mypath & "', CHANGED_WHO = '" & Environment.UserName & "' where GUID = " & folderwatch
            End If
            If ClassDatabase.Execute_non_Query(sql) Then
                folderwatch = ClassDatabase.Execute_Scalar("SELECT FOLDER_PATH FROM TBPMO_FOLDERWATCH_USER WHERE USER_ID = " & USER_GUID & " AND FOLDER_TYPE = 'SCAN'", True)

                CURRENT_SCAN_FOLDERWATCH = folderwatch
                Me.txtScanFolderWatch.Text = CURRENT_SCAN_FOLDERWATCH
            End If
            If FWSCAN_started = True Then
                ClassFolderWatcher.Restart_FolderWatchSCAN()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in CheckFolder:")
        End Try

    End Sub

    Private Sub btnSaveExclusionFiles_Click(sender As Object, e As EventArgs) Handles btnSaveExclusionFiles.Click
        Try
            DTEXCLUDE_FILES.AcceptChanges()
            DTEXCLUDE_FILES.WriteXml(PATH_FileExclusions)
            MsgBox("Changes saved.", MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Saving Exclusion files:")
        End Try

    End Sub

    Private Sub btnstartstop2_Click(sender As Object, e As EventArgs) Handles btnstartstop2.Click
        If CURRENT_SCAN_FOLDERWATCH <> "" Then
            CheckScanFolder(CURRENT_SCAN_FOLDERWATCH)
            CheckFWSCAN_State()
        End If
    End Sub
    Sub CheckFWSCAN_State()
        Select Case ClassFolderWatcher.StartStop_FolderWatchSCAN()
            Case 1
                'If USER_LANGUAGE = "de-DE" Then
                btnstartstop2.Text = "Überwachung stoppen"
                ' Else
                'btnstartstop2.Text = "Stop Hotfolder"
                ' End If
                btnstartstop2.Image = My.Resources.bell_delete
            Case 0
                ' If USER_LANGUAGE = "de-DE" Then
                btnstartstop2.Text = "Überwachung starten"
                'Else
                ' btnstartstop2.Text = "Start Hotfolder"
                'End If
                btnstartstop2.Image = My.Resources.bell_go
        End Select
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim result As MsgBoxResult
        If USER_LANGUAGE = "de-DE" Then
            result = MessageBox.Show("Wollen Sie die Applikationssprache nun auf '" & cmbLanguage.Text & "' ändern?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        Else
            result = MessageBox.Show("Would You like to change Your application language to '" & cmbLanguage.Text & "' ?", "Confirmation required:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        End If

        If result = MsgBoxResult.Yes Then
            formloaded = False
            Try
                Dim update As String = "UPDATE TBDD_USER SET [LANGUAGE] = '" & cmbLanguage.Text & "' WHERE GUID = " & USER_GUID
                USER_LANGUAGE = cmbLanguage.Text

                If ClassDatabase.Execute_non_Query(update, True) = True Then
                    SetLanguage()
                    If USER_LANGUAGE = "de-DE" Then
                        MsgBox("Die Sprache wurde erfolgreich geändert!", MsgBoxStyle.Information)
                    Else
                        MsgBox("The language was changed successfully!", MsgBoxStyle.Information)

                    End If
                    LANGUAGE_CHANGED = True
                End If
            Catch ex As Exception

            End Try
            formloaded = True
        End If
    End Sub
    Public Sub SetLanguage()
        Dim sz = Me.Size
        Dim pt = Me.Location
        Dim de = System.Globalization.CultureInfo.CurrentUICulture
        'Neue Sprache festlegen und entfernen aller Controls
        Thread.CurrentThread.CurrentUICulture = New CultureInfo(USER_LANGUAGE)
        Me.Controls.Clear()
        'Me.Events.Dispose()
        InitializeComponent()

        'Wiederherstellen der Fensterposition
        Me.Size = sz
        Me.Location = pt
    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 txtActualConnection_TextChanged(sender As Object, e As EventArgs) Handles txtActualConnection.TextChanged

    End Sub

    Private Sub cmbDatenbank_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbDatenbank.SelectedIndexChanged

    End Sub

    Private Sub txtPasswort_Leave(sender As Object, e As EventArgs) Handles txtPasswort.Leave

    End Sub
End Class