Imports System.ComponentModel
Imports System.IO
Imports System.Text.RegularExpressions
Imports DigitalData.EMLProfiler
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging
Imports Independentsoft.Email
Imports Independentsoft.Email.Mime

Public Class frmMain
    Private Logger As DigitalData.Modules.Logging.Logger
    Private Shared MyLogger As LogConfig
    Private _database As clsDatabase
    Private _Encryption As clsEncryption
    Private _windream As clsWindream_allgemein
    Private _email As clsEmail
    Private _emailIMAP As clsEmailIMAP
    Private _LoadInProgress As Boolean = True
    Private _RunwithLocalemail As Boolean = False
    Private _Localemail As String
    Private _SQLServerConString As String
    Private _Worklist As List(Of String)

    Public Sub New()

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

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

    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, My.Application.Info.CompanyName, My.Application.Info.ProductName)
            Logger = MyLogger.GetLogger()
            MyLogger.Debug = My.Settings.DEBUG
            InitDatabase()
            ToolStripProgressBar1.Visible = False
            Logger.Debug($"AppConfig is located at: [{AppDomain.CurrentDomain.SetupInformation.ConfigurationFile}]")
            If My.Settings.USE_WM Then
                _windream = New clsWindream_allgemein(MyLogger)
            End If

            _email = New clsEmail(MyLogger)
            _emailIMAP = New clsEmailIMAP(MyLogger, _SQLServerConString)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in FormLoad")
        End Try



        If Set_ConnectionStrings() Then
            Load_AllData()
            Check_Steps()
            Active_Color()
        End If
        If My.Settings.USE_WM Then
            ObjektTypenEintragen()
        End If

        _Encryption = New clsEncryption("!35452didalog=", MyLogger)
    End Sub
    Private Function Set_ConnectionStrings()
        Try

            Me.TBEMLP_POLL_PROFILESTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_PROCESSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_STEPSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_INDEXING_STEPSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBDD_EMAIL_ACCOUNTTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_HISTORYTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_CONFIGTableAdapter.Connection.ConnectionString = _SQLServerConString

            Return True
        Catch ex As Exception
            MsgBox("Unexpected Error in Set ConnectionStrings: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Sub Load_AllData()
        Try
            Me.TBDD_EMAIL_ACCOUNTTableAdapter.Fill(Me.MyDataset.TBDD_EMAIL_ACCOUNT)
            Me.TBEMLP_POLL_PROFILESTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROFILES)
            Me.TBEMLP_POLL_PROCESSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROCESS)
            Me.TBEMLP_POLL_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_STEPS)
            Me.TBEMLP_POLL_INDEXING_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_INDEXING_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_AllData: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Profiles()
        Try
            Me.TBEMLP_POLL_PROFILESTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROFILES)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Profiles: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Processes()
        Try
            Me.TBEMLP_POLL_PROCESSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROCESS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Processes: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Steps()
        Try
            Me.TBEMLP_POLL_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Steps: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_History()
        Try
            Me.TBEMLP_HISTORYTableAdapter.Fill(Me.MyDataset.TBEMLP_HISTORY)
        Catch ex As Exception
            MsgBox("Error in Load History: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_indexingSteps()
        Try
            Me.TBEMLP_POLL_INDEXING_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_INDEXING_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_indexingSteps: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Config()
        Try
            _LoadInProgress = True
            Me.TBEMLP_CONFIGTableAdapter.Fill(Me.MyDataset.TBEMLP_CONFIG)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Config: " & ex.Message, MsgBoxStyle.Critical)
        End Try
        _LoadInProgress = False
    End Sub
    Private Sub ObjektTypenEintragen()
        Try
            If IsNothing(_windream) Then
                Exit Sub
            End If
            ' Combobox leeren
            Me.WM_OBJEKTTYPEComboBox.Items.Clear()
            Dim result = _windream.GetObjecttypesAsStrings
            ' alle Objekttypen durchlaufen
            For Each oStr In result
                ' und in die Combobox eintragen
                Me.WM_OBJEKTTYPEComboBox.Items.Add(oStr)
            Next
        Catch ex As Exception
            MsgBox("Unexpected error in ObjektTypenEintragen", MsgBoxStyle.Critical)
        End Try

    End Sub

    Public Function InitDatabase()
        Try
            Dim dbResult As Boolean
            tslblstatus.BackColor = Color.Transparent
            If My.Settings.MyConnectionString <> String.Empty Then
                _SQLServerConString = My.Settings.MyConnectionString
                If _SQLServerConString.Contains("LOGIT_DMS") Then
                    _SQLServerConString.Replace("LOGIT_DMS", "DD_ECM")
                    Logger.Debug($"Replaced wrong Database in ConString ... ")
                End If
                Logger.Debug($"SQL-Server ConnString is [{_SQLServerConString}]")


                _database = New clsDatabase(MyLogger, My.Settings.MyConnectionString)
                dbResult = _database.Init(My.Settings.MyConnectionString)
            Else
                MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)

                TabControl1.SelectedIndex = 1
                tslblstatus.Text = "Please add a connection!"
                tslblstatus.BackColor = Color.Red
            End If
            If dbResult = False Then
                MsgBox("Error in init database. (Connection failed) More information in the logfile.", MsgBoxStyle.Critical)
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Init Database:")
            Return False
        End Try

    End Function
    Private Sub cmbDatenbank_Click(sender As Object, e As 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 & ";"
                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()
            MyConnectionString = con
            My.Settings.Save()
            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. The default database will be set!" & vbNewLine & "Check rights in sql-server for user: " & Me.txtUser.Text, MsgBoxStyle.Exclamation)
                cmbDatenbank.Text = "DD_ECM"
            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 BtnConnect_Click_1(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;Application Name=EMLProfiler_Client"
            Else
                con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";Application Name=EMLProfiler_Client"
            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
                'Set the construction string
                MyConnectionString = con
                My.Settings.MyConnectionString = MyConnectionString
                'csb.ConnectionString
                _database.Init(MyConnectionString)
                My.Settings.Save()

                If chkbxUserAut.Checked = False Then
                    Dim cipherText As String = _Encryption.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

                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
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MsgBox("Error in Connectionbuild: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        If _RunwithLocalemail = False Then
            MyLogger.Debug = True
            Dim _work As New clsWorker(MyLogger, _SQLServerConString, GUIDTextBox.Text, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USER, My.Settings.FB_PW, My.Settings.USE_WM)
            _work.Start_WorkingProfiles()

        Else
            For Each ofile As String In _Worklist
                _Localemail = ofile
                Logger.Info($"## Manual working on file {ofile} ... ")
                Dim _work As New clsWorker(MyLogger, _SQLServerConString, GUIDTextBox.Text, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USER, My.Settings.FB_PW, My.Settings.USE_WM, _Localemail)
                _work.Start_WorkingProfiles(True)
            Next

        End If
        Try
            'Delete all Tempfiles
            For Each _file In ClassCurrent.TEMP_FILES
                System.IO.File.Delete(_file)
            Next
            Try
                Dim oDiTempPath As New IO.DirectoryInfo(System.IO.Path.GetTempPath)
                Dim oaryFi As IO.FileInfo() = oDiTempPath.GetFiles()
                Dim ofi As IO.FileInfo

                For Each fi In oaryFi
                    fi.Delete()
                Next
            Catch ex As Exception
                If MyLogger.Debug = True Then
                    Logger.Warn($"Could not delete the tempfile: {ex.Message}")
                End If
            End Try
        Catch ex As Exception

        End Try
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Error IsNot Nothing Then
            '' if BackgroundWorker terminated due to error
            MessageBox.Show(e.Error.Message)
            'Label1.Text = "Error occurred!"

        ElseIf e.Cancelled Then
            '' otherwise if it was cancelled
            MessageBox.Show("Task cancelled!")
            '  Label1.Text = "Task Cancelled!"

        Else
            '' otherwise it completed normally
            MessageBox.Show("Manual Run completed!")
            'Label1.Text = "Error completed!"
        End If
        tsbtnRunProfiles.Enabled = True
        tsbtnRunLocalMail.Enabled = True
        ToolStripProgressBar1.Visible = False
    End Sub

    Private Sub tsbtnRunProfiles_Click(sender As Object, e As EventArgs) Handles tsbtnRunProfiles.Click
        _RunwithLocalemail = False
        If Not BackgroundWorker1.IsBusy Then
            tsbtnRunProfiles.Enabled = False
            tsbtnRunLocalMail.Enabled = False
            ToolStripProgressBar1.Visible = True
            BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub
    Private Sub ToolStripButton28_Click(sender As Object, e As EventArgs) Handles tsbtnRunLocalMail.Click
        If Not BackgroundWorker1.IsBusy Then
            Dim openFileDialog1 As New OpenFileDialog()

            ' openFileDialog1.InitialDirectory = "c:\"
            openFileDialog1.Filter = "Emails (*.eml)|*.eml|All files (*.*)|*.*"
            openFileDialog1.FilterIndex = 2
            openFileDialog1.RestoreDirectory = True
            openFileDialog1.Multiselect = True

            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                For Each oFile As String In openFileDialog1.FileNames
                    Dim oList As New List(Of String)
                    oList.Add(oFile)
                    _Worklist = oList
                Next
                _RunwithLocalemail = True
                tsbtnRunLocalMail.Enabled = False
                tsbtnRunProfiles.Enabled = False
                ToolStripProgressBar1.Visible = True
                BackgroundWorker1.RunWorkerAsync()
            End If



        End If

    End Sub
    Private Sub mWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        Me.ToolStripProgressBar1.Value = e.ProgressPercentage
    End Sub

    Private Sub btnShowLogpath_Click(sender As Object, e As EventArgs) Handles btnShowLogpath.Click
        Process.Start(MyLogger.LogDirectory)
    End Sub

    Private Sub TBEMLP_POLL_PROFILESBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBEMLP_POLL_PROFILESBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.MyDataset)

    End Sub

    Private Sub ToolStripButton9_Click(sender As Object, e As EventArgs) Handles ToolStripButton9.Click
        Load_AllData()
    End Sub

    Private Sub ToolStripButton10_Click(sender As Object, e As EventArgs) Handles ToolStripButton10.Click
        Load_Processes()
    End Sub

    Private Sub ToolStripButton8_Click(sender As Object, e As EventArgs) Handles ToolStripButton8.Click
        Try
            TBEMLP_POLL_PROCESSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_PROCESS.GetChanges Is Nothing = False Then
                CHANGED_WHOProcessTextBox.Text = Environment.UserName
                TBEMLP_POLL_PROCESSBindingSource.EndEdit()
                TBEMLP_POLL_PROCESSTableAdapter.Update(MyDataset.TBEMLP_POLL_PROCESS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Process: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub WM_OBJEKTTYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles WM_OBJEKTTYPEComboBox.SelectedIndexChanged
        If My.Settings.USE_WM Then
            Load_Indexdata()
        End If

    End Sub
    Sub Load_Indexdata()
        Try
            If Not IsNothing(WM_OBJEKTTYPEComboBox.Text) Then
                If WM_OBJEKTTYPEComboBox.Text = String.Empty Then
                    Exit Sub
                End If
                Me.WM_VECTOR_LOGComboBox.Items.Clear()
                Me.WM_IDX_BODY_TEXTComboBox.Items.Clear()
                INDEXNAMEIndexStepsComboBox.Items.Clear()

                Me.WM_VECTOR_LOGComboBox.Items.Add("")
                Me.WM_IDX_BODY_TEXTComboBox.Items.Add("")
                INDEXNAMEIndexStepsComboBox.Items.Add("")
                'Me.WM_REFERENCE_INDEXComboBox.Items.Clear()
                'Me.WM_REFERENCE_INDEXComboBox.Items.Add("")
                Dim indexe = _windream.GetIndicesByObjecttype(WM_OBJEKTTYPEComboBox.Text)
                If indexe IsNot Nothing Then
                    For Each index As String In indexe
                        Me.WM_VECTOR_LOGComboBox.Items.Add(index)
                        WM_IDX_BODY_TEXTComboBox.Items.Add(index)
                        INDEXNAMEIndexStepsComboBox.Items.Add(index)
                        ' WM_REFERENCE_INDEXComboBox.Items.Add(index)
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in load_WDIndices: ")
        End Try
    End Sub
    Private Sub ToolStripButton18_Click(sender As Object, e As EventArgs) Handles ToolStripButton18.Click
        Load_Steps()
    End Sub

    Private Sub WM_IMPORTCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles WM_IMPORTCheckBox.CheckedChanged
        If WM_IMPORTCheckBox.Checked Then
            GroupBox2.Enabled = True
        Else
            GroupBox2.Enabled = False
        End If
    End Sub

    Private Sub TBEMLP_POLL_PROFILESBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_PROFILESBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_PROFILES.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_PROCESSBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_PROCESSBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_PROCESS.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_STEPSBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_STEPSBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_STEPS.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub
    Private Sub TBDD_EMAIL_ACCOUNTBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBDD_EMAIL_ACCOUNTBindingSource.AddingNew
        MyDataset.TBDD_EMAIL_ACCOUNT.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_PROCESSBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBEMLP_POLL_PROCESSBindingSource.PositionChanged
        Check_Steps()
    End Sub
    Sub Check_Steps()
        If IsNumeric(GUIDProcessTextBox.Text) Then
            Dim oItemCount = TBEMLP_POLL_STEPSBindingSource.Count
            XtraTabPage2.Text = $"Working Steps ({oItemCount})"
        End If
    End Sub
    Sub Check_IndexingSteps()
        If IsNumeric(GUIDPollStepsTextBox.Text) Then
            Dim oItemCount = TBEMLP_POLL_INDEXING_STEPSBindingSource.Count
            XtraTabPage3.Text = $"Indexing Steps ({oItemCount})"
        End If
    End Sub
    Private Sub ToolStripButton27_Click(sender As Object, e As EventArgs) Handles ToolStripButton27.Click
        Save_email_Profile()
    End Sub
    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Try
            TBEMLP_POLL_PROFILESBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_PROFILES.GetChanges Is Nothing = False Then
                CHANGED_WHOProfilesTextBox.Text = Environment.UserName
                TBEMLP_POLL_PROFILESBindingSource.EndEdit()
                TBEMLP_POLL_PROFILESTableAdapter.Update(MyDataset.TBEMLP_POLL_PROFILES)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Process: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton17_Click(sender As Object, e As EventArgs) Handles ToolStripButton17.Click
        Try
            TBEMLP_POLL_STEPSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_STEPS.GetChanges Is Nothing = False Then
                CHANGED_WHOStepsTextBox.Text = Environment.UserName
                TBEMLP_POLL_STEPSBindingSource.EndEdit()
                TBEMLP_POLL_STEPSTableAdapter.Update(MyDataset.TBEMLP_POLL_STEPS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Steps: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub TBEMLP_POLL_STEPSBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBEMLP_POLL_STEPSBindingSource.PositionChanged
        Check_IndexingSteps()
    End Sub
    Private Sub ToolStripButton25_Click(sender As Object, e As EventArgs) Handles ToolStripButton25.Click
        Try
            TBEMLP_POLL_INDEXING_STEPSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_INDEXING_STEPS.GetChanges Is Nothing = False Then
                CHANGED_WHOIndexingStepsTextBox.Text = Environment.UserName
                TBEMLP_POLL_INDEXING_STEPSBindingSource.EndEdit()
                TBEMLP_POLL_INDEXING_STEPSTableAdapter.Update(MyDataset.TBEMLP_POLL_INDEXING_STEPS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Indexing Steps: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton26_Click(sender As Object, e As EventArgs) Handles ToolStripButton26.Click
        Load_indexingSteps()
    End Sub

    Private Sub XtraTabControl1_TabIndexChanged(sender As Object, e As EventArgs) Handles XtraTabControl1.TabIndexChanged

    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 0
                Check_Steps()
                If My.Settings.USE_WM Then
                    Load_Indexdata()
                End If

            Case 1
                Check_IndexingSteps()
            Case 2

        End Select
    End Sub

    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If My.Settings.USE_WM Then
            Load_Indexdata()
        End If

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        tsbtnRunProfiles.Visible = False
        tslblRefresh.BackColor = Color.Transparent
        tslblRefresh.Text = ""
        Select Case TabControl1.SelectedIndex
            Case 0
                tsbtnRunProfiles.Visible = True
            Case 1

                Load_Config()
            Case 2
                Load_History()
            Case 4
                Try
                    Dim osql = "SELECT * FROM TBDD_FUNCTION_REGEX WHERE UPPER(FUNCTION_NAME) IN (UPPER('EMAIL_PROFILER - RemoveHTMLText'),UPPER('EMAIL_PROFILER - RemoveHTMLText1'))"
                    Dim oDTFunctionRegex As DataTable = _database.Return_Datatable(osql)
                    txtRegex1.Text = oDTFunctionRegex.Rows(0).Item("REGEX")
                    txtRegex2.Text = oDTFunctionRegex.Rows(1).Item("REGEX")
                    txthtmlEmail.BackColor = Color.Wheat
                Catch ex As Exception
                    MsgBox("Error in Load Regex: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End Try
        End Select

    End Sub

    Private Sub ACTIVECheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles ACTIVECheckBox.CheckedChanged
        Active_Color()
    End Sub
    Sub Active_Color()
        If ACTIVECheckBox.Checked Then
            ACTIVECheckBox.BackColor = Color.LimeGreen

        Else
            ACTIVECheckBox.BackColor = Color.IndianRed
        End If
    End Sub

    Private Sub PROCESS_NAMEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles PROCESS_NAMEComboBox.SelectedIndexChanged
        If PROCESS_NAMEComboBox.SelectedIndex <> -1 Then
            Select Case PROCESS_NAMEComboBox.Text
                Case "ProcessManager"
                    txtSubjectExample.Text = "[ProcessManager][EA][DID#[%Dokument-ID]]"
                Case "Attachment Sniffer"
                    lblDownloadPath.Text = "Download-Path Attachments:"
                Case "ZugFeRD-Parser"
                    lblDownloadPath.Text = "Download-Path Attachments:"
                Case Else
                    txtSubjectExample.Text = ""
                    lblDownloadPath.Text = "Download-Path:"
            End Select
        End If
    End Sub

    Private Sub ToolStripButton34_Click(sender As Object, e As EventArgs) Handles ToolStripButton34.Click
        Load_History()
    End Sub

    Private Sub LOG_ERRORS_ONLYCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LOG_ERRORS_ONLYCheckBox.CheckedChanged
        If _LoadInProgress = True Then Exit Sub
        MyLogger.Debug = LOG_ERRORS_ONLYCheckBox.Checked
        My.Settings.Save()
        Dim upd = $"UPDATE TBEMLP_CONFIG SET CHANGED_WHO = '{Environment.UserName}',LOG_ERRORS_ONLY = '{LOG_ERRORS_ONLYCheckBox.Checked}' WHERE GUID = 1"
        _database.Execute_non_Query(upd)
        Load_Config()

    End Sub
    Sub Save_Config()
        Try
            TBEMLP_CONFIGBindingSource.EndEdit()
            If MyDataset.TBEMLP_CONFIG.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = Environment.UserName
                TBEMLP_CONFIGBindingSource.EndEdit()
                TBEMLP_CONFIGTableAdapter.Update(MyDataset.TBEMLP_CONFIG)

            End If
        Catch ex As Exception
            MsgBox("Error in Save_Config: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Save_email_Profile()
        Try
            TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
            If MyDataset.TBDD_EMAIL_ACCOUNT.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox1.Text = Environment.UserName
                TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
                TBDD_EMAIL_ACCOUNTTableAdapter.Update(MyDataset.TBDD_EMAIL_ACCOUNT)
                ToolStripStatusLabel1.Text = $"Email-Profil gespeichert [{Now.ToString}]"
            End If
        Catch ex As Exception
            MsgBox("Error in Save_EmailAccount: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub CHECK_INTERVALL_MINUTESNumericUpDown_ValueChanged(sender As Object, e As EventArgs) Handles CHECK_INTERVALL_MINUTESNumericUpDown.ValueChanged
        If _LoadInProgress = True Then Exit Sub
        Dim upd = $"UPDATE TBEMLP_CONFIG SET CHANGED_WHO = '{Environment.UserName}',CHECK_INTERVALL_MINUTES = {CHECK_INTERVALL_MINUTESNumericUpDown.Value} WHERE GUID = 1"
        _database.Execute_non_Query(upd)
        Load_Config()
    End Sub
    Private Function GetChildren(ByVal bodyParts As BodyPartCollection) As BodyPartCollection

        Dim children As New BodyPartCollection()

        For i As Integer = 0 To bodyParts.Count - 1
            children.Add(GetChildren(bodyParts(i).BodyParts))
            children.Add(bodyParts(i))
        Next

        Return children
    End Function

    Private Sub STEP_NAMEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles STEP_NAMEComboBox.SelectedIndexChanged
        Label9.Visible = False
        txtSubjectExample.Visible = False
        Select Case STEP_NAMEComboBox.Text
            Case "Easy Approval"
                Label9.Visible = True
                txtSubjectExample.Visible = True
            Case "Download Mail"
                COPY_2_HDDCheckBox.Checked = True
            Case Else

        End Select
    End Sub

    Private Sub btnFBD_DonwloadPath_Click(sender As Object, e As EventArgs) Handles btnFBD_DonwloadPath.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            PATH_EMAIL_TEMPTextBox.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub btnFBD_ErrorPath_Click(sender As Object, e As EventArgs) Handles btnFBD_ErrorPath.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            PATH_EMAIL_ERRORSTextBox.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim pwencrypted = _Encryption.EncryptData(txtnewpasswort.Text)
        EMAIL_PWTextBox.Text = pwencrypted
        Save_email_Profile()
        MsgBox("Passwort was encrypted!")
    End Sub

    Private Sub btnsendtestmail_Click(sender As Object, e As EventArgs) Handles btnsendtestmail.Click
        If txtTestmail.Text <> String.Empty Then
            My.Settings.Save()
            Dim PWPlain = _Encryption.DecryptData(EMAIL_PWTextBox.Text)

            If _email.Email_Send_Independentsoft("Testmail", "This is the body (text will be replaced within profile)", txtTestmail.Text,
                                EMAIL_FROMTextBox.Text, EMAIL_SMTPTextBox.Text, PORTTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text, "") = True Then
                MsgBox("Email was send successfully.", MsgBoxStyle.Information)
            Else
                MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btntestImap.Click
        My.Settings.Save()
        Dim oSQL = $"SELECT * FROM TBDD_EMAIL_ACCOUNT WHERE GUID = {EMAILIDTextBox.Text}"
        Dim oDT As DataTable = _database.Return_Datatable(oSQL)
        If Not IsNothing(oDT) Then
            If oDT.Rows.Count = 1 Then

                Dim PWPlain = _Encryption.DecryptData(oDT.Rows(0).Item("EMAIL_PW"))
                'Logger.Debug($"PWis !{PWPlain}35452dd=")
                Dim oResult
                'If chkS22.Checked Then
                oResult = _emailIMAP.FetchIMAPMessagesS22(oDT.Rows(0).Item("EMAIL_SMTP"), oDT.Rows(0).Item("PORT_IN"), oDT.Rows(0).Item("EMAIL_USER"), PWPlain, txtInboxname.Text, True, chkDeleteMail.Checked,
                                                           ARCHIVE_FOLDERTextBox.Text)
                'Else
                'oResult = _emailIMAP.FetchIMAPMessagesIsoft(EMAIL_SMTPTextBox.Text, PORT_INTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, txtInboxname.Text,
                'ARCHIVE_FOLDERTextBox.Text, Path.Combine(My.Application.Info.DirectoryPath, "Log") & "\IsoftLog.txt", True, chkDeleteMail.Checked)
                'End If


                If oResult = False Then
                    MsgBox("Access Imap NOT successfull", MsgBoxStyle.Critical)
                Else
                    MsgBox("Test Successful!", MsgBoxStyle.Information)
                End If
            End If
        End If


    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        My.Settings.Save()
        Dim PWPlain = _Encryption.DecryptData(EMAIL_PWTextBox.Text)
        _email.TEST_POP3_COLLECT(EMAIL_SMTPTextBox.Text, PORTTextBox.Text, EMAIL_USERTextBox.Text, PWPlain)
    End Sub

    Private Sub btnTestRegEx_Click(sender As Object, e As EventArgs) Handles btnTestRegEx.Click
        txtResultRegEx.Text = ""
        Try
            My.Settings.Save()
            txtResultRegEx.BackColor = Color.WhiteSmoke
            ' Instantiate the regular expression object.
            Dim oReg As Regex = New Regex(txtRegex1.Text, RegexOptions.IgnoreCase)
            Dim oMatch As Match = oReg.Match(txthtmlEmail.Text)
            Dim oClearedBodyText = txthtmlEmail.Text
            Do While oMatch.Success
                oClearedBodyText = oClearedBodyText.Replace(oMatch.Value, "")
                'Dim g As Group = m.Groups(1)
                'If g.ToString.StartsWith("&") = False Then
                '    TEMP_HTML_RESULTS.Add(g.ToString())
                'End If

                oMatch = oMatch.NextMatch()
            Loop
            Logger.Info($"Cleared bodytext after Regex1 is: {oClearedBodyText}")
            Dim oReg2 As Regex = New Regex(txtRegex2.Text, RegexOptions.IgnoreCase)
            Dim oMatch2 As Match = oReg2.Match(oClearedBodyText)

            Do While oMatch2.Success
                oClearedBodyText = oClearedBodyText.Replace(oMatch2.Value, "")
                'Dim g As Group = m.Groups(1)
                'If g.ToString.StartsWith("&") = False Then
                '    TEMP_HTML_RESULTS.Add(g.ToString())
                'End If

                oMatch2 = oMatch2.NextMatch()
            Loop
            Logger.Info($"Cleared bodytext after Regex2 is: {oClearedBodyText}")
            txtResultRegEx.Text = oClearedBodyText
            txtResultRegEx.BackColor = Color.Yellow
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub btnsaveRegex_Click_1(sender As Object, e As EventArgs) Handles btnsaveRegex.Click
        tslblRefresh.BackColor = Color.Transparent
        Dim upd = $"UPDATE TBDD_FUNCTION_REGEX SET REGEX = '{txtRegex1.Text}' WHERE UPPER(FUNCTION_NAME) = UPPER('EMAIL_PROFILER - RemoveHTMLText')"
        If _database.Execute_non_Query(upd) = True Then
            tslblRefresh.Text = "Regex1 saved - " & Now.ToString
            tslblRefresh.BackColor = Color.Yellow
        Else
            tslblRefresh.Text = "Regex1 NOT saved - Check Your log: " & Now.ToString
            tslblRefresh.BackColor = Color.Transparent
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try
            txthtmlEmail.Text = ""
            txthtmlEmail.BackColor = Color.Wheat
            Dim oOpenFileDialog1 As New OpenFileDialog()

            ' openFileDialog1.InitialDirectory = "c:\"
            oOpenFileDialog1.Filter = "Emails (*.eml)|*.eml|All files (*.*)|*.*"
            oOpenFileDialog1.FilterIndex = 2
            oOpenFileDialog1.RestoreDirectory = True

            If oOpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim oMsg_email As New Independentsoft.Email.Mime.Message(oOpenFileDialog1.FileName)
                Dim oBodyText As String = ""
                If IsNothing(oMsg_email.Body) Then
                    Dim oAllBodyParts As New BodyPartCollection()
                    oAllBodyParts.Add(oMsg_email.BodyParts)
                    oAllBodyParts.Add(GetChildren(oMsg_email.BodyParts))
                    For Each bodyPart As BodyPart In oAllBodyParts
                        If bodyPart.ContentType IsNot Nothing AndAlso bodyPart.ContentType.Type = "text" AndAlso bodyPart.ContentType.SubType = "plain" Then
                            If oBodyText = String.Empty Then
                                Logger.Debug(String.Format("BODY1-Text is....#{0}", bodyPart.Body))
                                oBodyText = bodyPart.Body
                            Else
                                Continue For
                            End If
                        ElseIf bodyPart.ContentType IsNot Nothing AndAlso bodyPart.ContentType.Type = "text" AndAlso bodyPart.ContentType.SubType = "html" Then
                            If oBodyText = String.Empty Then
                                oBodyText = bodyPart.Body
                                Logger.Debug(String.Format("bodyhtml....#{0}", bodyPart.Body))
                            Else
                                Continue For
                            End If
                            Logger.Debug(String.Format("bodyhtml....#{0}", bodyPart.Body))
                        End If
                    Next
                    If oBodyText = "" Then
                        MsgBox("No html-body extractable?!")
                    Else
                        txthtmlEmail.Text = oBodyText
                        txthtmlEmail.BackColor = Color.Yellow
                    End If
                Else
                    txthtmlEmail.Text = oMsg_email.Body
                    txthtmlEmail.BackColor = Color.Yellow
                End If

            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        tslblRefresh.BackColor = Color.Transparent
        Dim upd = $"UPDATE TBDD_FUNCTION_REGEX SET REGEX = '{txtRegex2.Text}' WHERE UPPER(FUNCTION_NAME) = UPPER('EMAIL_PROFILER - RemoveHTMLText1')"
        If _database.Execute_non_Query(upd) = True Then
            tslblRefresh.Text = "Regex2 saved - " & Now.ToString
            tslblRefresh.BackColor = Color.Yellow
        Else
            tslblRefresh.Text = "Regex2 NOT saved - Check Your log: " & Now.ToString
            tslblRefresh.BackColor = Color.Transparent
        End If
    End Sub

    Private Sub COPY_2_HDDCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles COPY_2_HDDCheckBox.CheckedChanged
        If COPY_2_HDDCheckBox.Checked Then
            PATH_ORIGINALTextBox.Enabled = True
        Else
            PATH_ORIGINALTextBox.Enabled = False
        End If
    End Sub

    Private Sub frmMain_ImeModeChanged(sender As Object, e As EventArgs) Handles Me.ImeModeChanged

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim _ss2email As New Email(MyLogger)
        If txtTestmail.Text <> String.Empty Then
            My.Settings.Save()
            Dim PWPlain = _Encryption.DecryptData(EMAIL_PWTextBox.Text)

            If _ss2email.NewEmail(txtTestmail.Text, "Testmail SSMail", "This is the body (text will be replaced within profile)", EMAIL_FROMTextBox.Text, EMAIL_SMTPTextBox.Text, PORTTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text, "GUI Test", "") = True Then
                MsgBox("Email was send successfully.", MsgBoxStyle.Information)
            Else
                MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
            End If
        End If
    End Sub

    Private Sub chkS22_CheckedChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        My.Settings.Save()
        Dim PWPlain = _Encryption.DecryptData(EMAIL_PWTextBox.Text)
        'Logger.Debug($"PWis !{PWPlain}35452dd=")
        Dim oResult

        oResult = _emailIMAP.IMAP_Set2Seen(EMAIL_SMTPTextBox.Text, PORT_INTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, Path.Combine(My.Application.Info.DirectoryPath, "Log") & "\IsoftLog.txt")



        If oResult = False Then
            MsgBox("Access Imap NOT successfull", MsgBoxStyle.Critical)
        Else
            MsgBox("Test Successful!", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub COMMENTTextBox_Leave(sender As Object, e As EventArgs) Handles COMMENTTextBox.Leave
        Dim separatorIndex = COMMENTTextBox.Text.IndexOf(".")
        TextBox1.Text = COMMENTTextBox.Text.Substring(separatorIndex, COMMENTTextBox.Text.Length - 1)
    End Sub
End Class
