Imports System.ServiceProcess
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging
Imports DD_WMResulthandler
Imports System.Net.Mail
Imports System.Net
Imports DigitalData.Modules.Messaging.Mail

Public Class frmMain
    Private _windream As clsWindream_allgemein
    Private _database As clsDatabase
    Private _profil As clsProfil
    Dim MyLogger As LogConfig
    Dim Logger As Logger
    Dim switchRecord As Boolean = True
    Private Sub TBPROFILBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TBPROFILBindingNavigatorSaveItem.Click
        Save_Profil()
    End Sub


    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: Diese Codezeile lädt Daten in die Tabelle "MyDataset.TBDD_EMAIL_ACCOUNT". Sie können sie bei Bedarf verschieben oder entfernen.

        'If My.Settings.myConnString = String.Empty Then
        '    Dim dbPath As String = Application.StartupPath & "\Database\wdResultHandler.db3"
        '    If IO.File.Exists(dbPath) Then
        '        My.Settings.myConnString = dbPath
        '        My.Settings.Save()
        '    Else
        '        MsgBox("Achtung: Die SQLite-Database File exisitiert nicht am angegebenen Ort: " & vbNewLine & dbPath, MsgBoxStyle.Critical, "Fehler:")
        '        DB_Path()
        '    End If
        'End If
        MyLogger = New LogConfig(LogConfig.PathType.CustomPath,
                                       Application.LocalUserAppDataPath & "\Log",
                                        Nothing,
                                        My.Application.Info.CompanyName,
                                        My.Application.Info.ProductName)
        MyLogger.Debug = True
        Logger = MyLogger.GetLogger()
        Load_Constring()
        _database = New clsDatabase(MyLogger)
        Logger.Info("WMKonfig started: " & Now.ToString)
        Try
            ' Windream instanziieren
            _windream = New clsWindream_allgemein(MyLogger)
            'Windream initialisieren (Connection, Session, ... aufbauen)
            _windream.Init()
        Catch ex As Exception
            MsgBox("Fehler bei Initialisieren von windream: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Achtung:")
        End Try

        Load_Profil()
        Load_Uebersicht()
        ToolStripStatusLabelVersion.Text = String.Format("Version {0}", My.Application.Info.Version.ToString)
    End Sub
    Sub Load_Uebersicht()
        ' Try
        Dim DT As DataTable = MyDataset.TBWMRH_PROFIL
        '    ClassDIProfile.Init()
        Dim Count As Integer = 0
        ListViewProfile.Items.Clear()


        Dim running = CheckIfRunning("DDWDResultHandler")
        If running = False Then
            ListViewProfile.Columns(3).Width = 150
        Else
            ListViewProfile.Columns(3).Width = 80
        End If
        For Each row As DataRow In DT.Rows
            ListViewProfile.Items.Add(row.Item("Profilname"))
            If running = False Then
                ListViewProfile.Items(Count).ImageIndex = 2
            Else
                If CBool(row.Item("Aktiv")) = True Then
                    ListViewProfile.Items(Count).ImageIndex = 0
                Else
                    ListViewProfile.Items(Count).ImageIndex = 1
                End If
            End If
            Try
                ListViewProfile.Items(Count).SubItems.Add(row.Item("Aktiv"))
            Catch ex As Exception

            End Try

            ListViewProfile.Items(Count).SubItems.Add(row.Item("Letzter_Durchlauf"))
            If running = False Then
                ListViewProfile.Items(Count).SubItems.Add("Service stopped")
            Else
                If CBool(row.Item("Running")) = True Then
                    ListViewProfile.Items(Count).SubItems.Add("Running")
                Else
                    ListViewProfile.Items(Count).SubItems.Add("Waiting")
                End If
            End If

            Count += 1
        Next

        'Catch ex As Exception
        '    MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden der Dateiimport-Profileiste")
        'End Try
    End Sub
    Private Function CheckIfRunning(sServiceName As String) As Boolean
        Try
            Dim sc As New ServiceController(sServiceName)
            If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
                ' Service is not running
                Return False
            Else
                ' Service is running()
                Return True
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Fehler inCheckIfRunning")
            Return False
        End Try
    End Function
    Sub Load_Constring()
        My.Settings.Save()
        Me.TBWMRH_KONFIGURATIONTableAdapter.Connection.ConnectionString = My.Settings.SQLSERVER_CS
        Me.TBWMRH_PROFILTableAdapter.Connection.ConnectionString = My.Settings.SQLSERVER_CS
        Me.TBWMRH_PROFIL_JOBTableAdapter.Connection.ConnectionString = My.Settings.SQLSERVER_CS
        Me.TBWMRH_PROFIL_FILE_JOBTableAdapter.Connection.ConnectionString = My.Settings.SQLSERVER_CS
        Me.TBDD_EMAIL_ACCOUNTTableAdapter.Connection.ConnectionString = My.Settings.SQLSERVER_CS

        Load_Grundkonfig()
    End Sub
    Sub Load_Grundkonfig()
        Try
            'TODO: Diese Codezeile lädt Daten in die Tabelle "MyDataset.TBWMRH_TBKONFIGURATION". Sie können sie bei Bedarf verschieben oder entfernen.
            Me.TBWMRH_KONFIGURATIONTableAdapter.Fill(Me.MyDataset.TBWMRH_KONFIGURATION)
            clsCURRENT.LogErrorsOnly = MyDataset.TBWMRH_KONFIGURATION.Rows(0).Item("LOG_ERRORS_ONLY")
            clsCURRENT.WDLAUFWERK = MyDataset.TBWMRH_KONFIGURATION.Rows(0).Item("WD_LAUFWERK")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load_Konfiguration:")
        End Try
    End Sub
    Sub Load_Profil()
        Try
            switchRecord = True
            Me.TBWMRH_PROFILTableAdapter.Fill(Me.MyDataset.TBWMRH_PROFIL)

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load_Profil:")
        End Try
        switchRecord = False
    End Sub
    Private Sub ObjekttypenEintragen()
        Me.ObjekttypComboBox.Items.Clear()
        Try
            Dim oDokumentTypen As WINDREAMLib.WMObjects = Me._windream.GetObjecttypesAsObjects()
            If oDokumentTypen Is Nothing Then Exit Sub
            For Each aType In oDokumentTypen
                Me.ObjekttypComboBox.Items.Add(aType.aName)
            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei ObjekttypenEintragen")
        End Try

    End Sub
    Sub Save_Profil()
        Try
            Select Case cmbTimeTyp.SelectedIndex
                Case 0
                    RunTextBox.Text = "INTV;" & NumericUpDown.Value
                Case 1
                    RunTextBox.Text = "TIME;" & dtp_Time.Text
            End Select

            Me.TBWMRH_PROFILBindingSource.EndEdit()
            If MyDataset.TBWMRH_PROFIL.GetChanges Is Nothing = False Then
                Me.GEAENDERTWERTextBox.Text = Environment.UserName
                Me.TBWMRH_PROFILBindingSource.EndEdit()
                Me.TBWMRH_PROFILTableAdapter.Update(MyDataset.TBWMRH_PROFIL)
                statuslabel(True, "Profil erfolgreich gespeichert - " & Now)
            Else
                statuslabel(False, "")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Save_Profil:")
        End Try

    End Sub
    Sub statuslabel(visible As Boolean, Text As String)
        Me.tsstatus.Visible = visible
        If visible = True Then
            tsstatus.BackColor = Color.Yellow
        Else
            tsstatus.BackColor = Color.Transparent
        End If
        Me.tsstatus.Text = Text
    End Sub
    Private Sub btnaddSearch_Click(sender As Object, e As EventArgs) Handles btnaddSearch.Click
        With OpenFileDialog1
            ' Do
            .Filter = " windream-Suche|*.wdf|Alle Dateien|*.*"
            .FilterIndex = 1
            .Title = "Pfad zur windream-suche:"
            If .ShowDialog() = DialogResult.OK Then
                Me.WindreamSucheTextBox.Text = .FileName
            End If
        End With
    End Sub

    Private Sub TBPROFILBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs)
        MyDataset.TBWMRH_PROFIL.ERSTELLTWERColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBPROFILBindingSource_CurrentItemChanged(sender As Object, e As EventArgs)
        statuslabel(True, "TBPROFILBindingSource.CurrentItemChanged")
    End Sub

    Private Sub TBPROFILBindingSource_PositionChanged(sender As Object, e As EventArgs)
        statuslabel(True, "TBPROFILBindingSource.PositionChanged - " & GUIDTextBox.Text)

        'obj.SelectedIndex = cmbObjekttypen.FindStringExact()
    End Sub

    Private Sub TabControlMain_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControlMain.SelectedIndexChanged
        Select Case TabControlMain.SelectedIndex
            Case 0
                Load_Profil()
                Load_Uebersicht()
            Case 1
                ObjekttypenEintragen()
                Load_Profil()
            Case 2
                Load_Grundkonfig()
            Case 3
                load_Emails()
        End Select
    End Sub
    Private Sub TBPROFILBindingSource_BindingComplete(sender As Object, e As BindingCompleteEventArgs)
        statuslabel(True, "TBPROFILBindingSource.BindingComplete - " & GUIDTextBox.Text)
    End Sub
    Sub load_Emails()
        Try
            Me.TBDD_EMAIL_ACCOUNTTableAdapter.Fill(Me.MyDataset.TBDD_EMAIL_ACCOUNT)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load Emails:")
        End Try
    End Sub
    Sub Checkbox_Days()
        If switchRecord = True Then
            Exit Sub
        End If
        Dim days As String
        If CheckBox1.Checked Then
            days = "1"
        Else
            days = "0"
        End If
        If CheckBox2.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        If CheckBox3.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        If CheckBox4.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        If CheckBox5.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        If CheckBox6.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        If CheckBox7.Checked Then
            days = days & "1"
        Else
            days = days & "0"
        End If
        Me.DayTextBox.Text = days
    End Sub
    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
        Checkbox_Days()
    End Sub
    Private Sub CheckBox3_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox3.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub CheckBox4_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox4.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub CheckBox5_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox5.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub CheckBox6_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox6.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub CheckBox7_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox7.CheckedChanged
        Checkbox_Days()
    End Sub

    Private Sub DayTextBox_TextChanged(sender As Object, e As EventArgs) Handles DayTextBox.TextChanged
        If DayTextBox.Text <> String.Empty Then
            switchRecord = True
            CheckBox1.Checked = False
            CheckBox2.Checked = False
            CheckBox3.Checked = False
            CheckBox4.Checked = False
            CheckBox5.Checked = False
            CheckBox6.Checked = False
            CheckBox7.Checked = False

            'Markieren der Checkboxen'
            If DayTextBox.Text.Substring(0, 1) = 1 Then
                CheckBox1.Checked = True
            End If
            If DayTextBox.Text.Substring(1, 1) = 1 Then
                CheckBox2.Checked = True
            End If
            If DayTextBox.Text.Substring(2, 1) = 1 Then
                CheckBox3.Checked = True
            End If
            If DayTextBox.Text.Substring(3, 1) = 1 Then
                CheckBox4.Checked = True
            End If
            If DayTextBox.Text.Substring(4, 1) = 1 Then
                CheckBox5.Checked = True
            End If
            If DayTextBox.Text.Substring(5, 1) = 1 Then
                CheckBox6.Checked = True
            End If
            If DayTextBox.Text.Substring(6, 1) = 1 Then
                CheckBox7.Checked = True
            End If
            switchRecord = False
        End If

    End Sub

    Private Sub RunTextBox_TextChanged(sender As Object, e As EventArgs) Handles RunTextBox.TextChanged
        Dim arr As String()
        arr = RunTextBox.Text.Split(";")

        If RunTextBox.Text.Contains("TIME") Then
            dtp_Time.Value = CDate("01.01.1900 " & arr(1))
            Me.cmbTimeTyp.SelectedIndex = 1
            Me.dtp_Time.Visible = True
            Me.NumericUpDown.Visible = False
            lblTimeIntervall.Text = "Uhrzeit:"
        ElseIf RunTextBox.Text.Contains("INTV") Then 'INTV
            If arr(1) = "" Then arr(1) = "5"
            NumericUpDown.Value = arr(1)
            Me.cmbTimeTyp.SelectedIndex = 0
            Me.dtp_Time.Visible = False
            Me.NumericUpDown.Visible = True
            lblTimeIntervall.Text = "Intervall (Minute):"
        End If


    End Sub

    Private Sub cmbTimeTyp_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbTimeTyp.SelectedIndexChanged
        Select Case cmbTimeTyp.SelectedIndex
            Case 0
                Me.dtp_Time.Visible = False
                Me.NumericUpDown.Visible = True
                RunTextBox.Text = "INTV;" & NumericUpDown.Value
            Case 1
                Me.dtp_Time.Visible = True
                Me.NumericUpDown.Visible = False
                RunTextBox.Text = "TIME;" & dtp_Time.Text
        End Select
    End Sub

    Private Sub Load_Jobs(ProfilID As Integer)
        Try
            Me.TBWMRH_PROFIL_JOBTableAdapter.Fill(Me.MyDataset.TBWMRH_PROFIL_JOB, ProfilID)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load Jobs:")
        End Try
    End Sub
    Private Sub Load_FILE_JOBS(Profil_ID As Integer)
        Try
            Me.TBWMRH_PROFIL_FILE_JOBTableAdapter.Fill(Me.MyDataset.TBWMRH_PROFIL_FILE_JOB, Profil_ID)
            Me.STRING1ComboBox.Items.Clear()
            cmbFileJob_WHIndexe.Items.Clear()
            Dim indexe = _windream.GetIndicesByObjecttype(ObjekttypComboBox.Text)
            If indexe IsNot Nothing Then
                For Each index As String In indexe
                    Me.STRING1ComboBox.Items.Add(index)
                    cmbFileJob_WHIndexe.Items.Add(index)
                Next
            End If
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load File-Jobs:")
        End Try

    End Sub
    Private Sub GUIDTextBox_TextChanged(sender As Object, e As EventArgs) Handles GUIDTextBox.TextChanged
        Load_Jobs()
    End Sub
    Sub Load_Jobs()
        If GUIDTextBox.Text <> String.Empty Then
            Load_Jobs(GUIDTextBox.Text)
            Load_FILE_JOBS(GUIDTextBox.Text)
        End If
    End Sub
    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
        Save_PROFIL_JOB()
    End Sub
    Sub Save_PROFIL_JOB()
        Try
            Me.TBWMRH_PROFIL_JOBBindingSource.EndEdit()
            If MyDataset.TBWMRH_PROFIL_JOB.GetChanges Is Nothing = False Then
                Me.GEAENDERTWERTextBox1.Text = Environment.UserName
                Me.TBWMRH_PROFIL_JOBBindingSource.EndEdit()
                Me.TBWMRH_PROFIL_JOBTableAdapter.Update(MyDataset.TBWMRH_PROFIL_JOB)
                statuslabel(True, "Profil-JOB erfolgreich gespeichert - " & Now)
            Else
                statuslabel(False, "")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Save PROFIL-JOB:")
        End Try
    End Sub
    Sub Save_File_JOB()
        Try
            Me.TBWMRH_PROFIL_FILE_JOBBindingSource.EndEdit()
            If MyDataset.TBWMRH_PROFIL_FILE_JOB.GetChanges Is Nothing = False Then
                Me.GEAENDERTWERTextBox2.Text = Environment.UserName
                Me.TBWMRH_PROFIL_FILE_JOBBindingSource.EndEdit()
                Me.TBWMRH_PROFIL_FILE_JOBTableAdapter.Update(MyDataset.TBWMRH_PROFIL_FILE_JOB)
                statuslabel(True, "File-JOB erfolgreich gespeichert - " & Now)
            Else
                statuslabel(False, "")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Save File-JOB:")
        End Try
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Sind Sie sicher dass Sie diesen Job löschen wollen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Me.TBWMRH_PROFIL_JOBTableAdapter.Delete(Me.PROFILJOB_GUIDTextBox.Text)
            Load_Jobs(Me.GUIDTextBox.Text)
            statuslabel(True, "Job wurde erfolgreich gelöscht! - " & Now)
        End If
    End Sub

    Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorDeleteItem.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Sind Sie sicher dass Sie dieses Profil löschen wollen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Me.TBWMRH_PROFIL_JOBTableAdapter.DeleteforPROFIL(Me.GUIDTextBox.Text)
            Me.TBWMRH_PROFIL_FILE_JOBTableAdapter.DeleteForProfil(Me.GUIDTextBox.Text)
            Me.TBWMRH_PROFILTableAdapter.Delete(Me.GUIDTextBox.Text)
            Load_Profil()
            statuslabel(True, "Profil wurde erfolgreich gelöscht! - " & Now)
        End If
    End Sub

    Private Sub JOB_TYPComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles JOB_TYPComboBox.SelectedIndexChanged
        Show_String_Lables()
    End Sub
    Sub Show_String_Lables()
        btnJOB_addSpeicherort.Visible = False
        lblString1.Text = ""
        lblString2.Text = ""
        lblString3.Text = ""
        lblString4.Text = ""
        lblString5.Text = ""
        BOOL1CheckBox.Visible = False
        STRING1TextBox.Visible = False
        STRING1TextBox.Size = New Size(466, 22)
        STRING2TextBox.Visible = False
        STRING3TextBox.Visible = False
        STRING4TextBox.Visible = False
        ' STRING3TextBox.Size = New Size(400, 22)
        STRING3TextBox.Multiline = False
        STRING3TextBox1.Visible = False
        STRING5TextBox.Visible = False
        STRING2ComboBox.Visible = False

        Select Case JOB_TYPComboBox.Text.ToUpper
            Case "Export HDD".ToUpper
                lblString1.Text = "Speicherort für windream-Ergebnisse:"
                STRING1TextBox.Visible = True
                btnJOB_addSpeicherort.Visible = True
            Case "Create Mail Attachment".ToUpper
                lblString1.Text = "Email-Empfänger:"
                STRING1TextBox.Visible = True
                lblString2.Text = "Email-Betreff:"
                STRING2TextBox.Visible = True
                lblString3.Text = "Email-Body:"
                lblString4.Text = "Email-Profil:"
                lblString4.Visible = True
                STRING3TextBox.Visible = False
                STRING3TextBox1.Visible = True
                STRING4TextBox.Visible = True
                STRING5TextBox.Visible = True
                lblString5.Text = "Benennung Datei:"
                lblString5.Visible = True
            Case "BNS json Download".ToUpper 'json BNS
                lblString1.Text = "User Kunde:"
                STRING1TextBox.Visible = True
                lblString2.Text = "BNS Kundennummer:"
                STRING2TextBox.Visible = True
            Case "Concat Files to one pdf".ToUpper ' Concat Files to one pdf
                lblString1.Text = "Name und Speicherort der zusammengefügten PDF-Datei:"
                STRING1TextBox.Visible = True
                btnJOB_addSpeicherort.Visible = True
                lblString2.Text = "Löschen der exportierten Dateien (Ja/Nein)"
                STRING2TextBox.Visible = True
            Case "Send concatted file via mail".ToUpper
                lblString1.Text = "Email-Empfänger:"
                STRING1TextBox.Visible = True
                lblString2.Text = "Email-Betreff:"
                STRING2TextBox.Visible = True
                lblString3.Text = "Email-Body:"
                STRING3TextBox.Visible = False
                STRING3TextBox1.Visible = True
                lblString4.Text = "Email-Profil:"
                STRING4TextBox.Visible = True
            Case "Send to printer".ToUpper
                lblString1.Text = "Netzwerkpfad/Name des Druckers:"
                STRING1TextBox.Visible = True
            Case "Send InfoMail with WM-Search".ToUpper
                lblString1.Text = "Email-Empfänger:"
                STRING1TextBox.Visible = True
                lblString2.Text = "Email-Betreff:"
                STRING2TextBox.Visible = True
                lblString3.Text = "Email-Body:"
                STRING3TextBox.Visible = False
                STRING3TextBox1.Visible = True
                lblString4.Text = "Email-Profil:"
                STRING4TextBox.Visible = True
                lblString5.Text = "Pfad zu WM-Suche:"
                STRING5TextBox.Visible = True
            Case "Archive Document X years from Indexdate".ToUpper
                lblString1.Text = "Archivdauer in Jahren:"
                STRING1TextBox.Size = New Size(53, 22)
                STRING1TextBox.Visible = True
                lblString2.Text = "Index mit Startdatum:"
                STRING2ComboBox.Items.Clear()
                Dim indexe = _windream.GetIndicesByObjecttype(ObjekttypComboBox.Text)
                If indexe IsNot Nothing Then
                    For Each index As String In indexe
                        Select Case _windream.GetTypeOfIndexAsIntByName(index)
                            Case 3 'Float
                                '
                            Case 4
                            '    Me.STRING2ComboBox.Items.Add(index)
                            Case 1
                            '    Me.STRING2ComboBox.Items.Add(index)
                            Case 2
                            '    Me.STRING2ComboBox.Items.Add(index)
                            Case 5
                                Me.STRING2ComboBox.Items.Add(index)
                            Case Else
                                'MsgBox(_windream.GetTypeOfIndexAsIntByName(index))
                        End Select


                    Next
                End If
                STRING2ComboBox.Visible = True
                BOOL1CheckBox.Text = "Nach Ablauf der Archivierungsdauer automatisch löschen"
                'BOOL1CheckBox.Visible = True

        End Select
    End Sub
    Private Sub btnJOB_addSpeicherort_Click(sender As Object, e As EventArgs) Handles btnJOB_addSpeicherort.Click
        With FolderBrowserDialog1
            ' Do
            .Description = "Speicherort für Ergebnis-Dokumente"
            If .ShowDialog() = DialogResult.OK Then
                Me.STRING1TextBox.Text = .SelectedPath
            End If
        End With
    End Sub

    Private Sub ToolStripButton9_Click(sender As Object, e As EventArgs) Handles ToolStripButton9.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Sind Sie sicher dass Sie diesen File-Job löschen wollen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Me.TBWMRH_PROFIL_FILE_JOBTableAdapter.Delete(Me.GUIDTextBox2.Text)
            Load_FILE_JOBS(Me.GUIDTextBox.Text)
            statuslabel(True, "File-Job wurde erfolgreich gelöscht! - " & Now)
        End If
    End Sub

    Private Sub ToolStripButton14_Click(sender As Object, e As EventArgs) Handles ToolStripButton14.Click
        Save_File_JOB()
    End Sub

    Private Sub STEP_TYPComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles STEP_TYPComboBox.SelectedIndexChanged
        cmbFileJob_WHIndexe.Visible = False
        btnFileJob_addIndex.Visible = False
        Me.btnaddDatetime.Visible = False
        STRING1TextBoxFile_Job.Visible = False
        STRING2TextBoxProfil_FileJob.Visible = False
        lblString2FileJobs.Visible = False
        btnTestCon.Visible = False
        lblndexname.Visible = False
        STRING1TextBoxFile_Job.Size = New Size(299, 22)
        STRING1TextBoxFile_Job.Anchor = AnchorStyles.Left Or AnchorStyles.Top
        STRING2TextBoxProfil_FileJob.Size = New Size(455, 22)
        STRING2TextBoxProfil_FileJob.Anchor = AnchorStyles.Left Or AnchorStyles.Top
        If STEP_TYPComboBox.SelectedIndex <> -1 Then
            Select Case STEP_TYPComboBox.SelectedIndex
                Case 0
                    lblString1FileJobs.Text = "Indexname"
                    STRING1ComboBox.Visible = True

                    lblString2FileJobs.Text = "Wert"
                    lblString2FileJobs.Visible = True
                    STRING2TextBoxProfil_FileJob.Visible = True
                    Me.btnaddDatetime.Visible = True

                Case 1
                    Renamewithindex()
                Case 2
                    Renamewithindex()
                Case 3 'Oracle
                    btnTestCon.Visible = True
                    lblString1FileJobs.Text = "Connection String Oracle"
                    lblString2FileJobs.Text = "Command Oracle"
                    STRING1TextBoxFile_Job.Visible = True
                    STRING2TextBoxProfil_FileJob.Visible = True
                    lblString2FileJobs.Visible = True
                    STRING1TextBoxFile_Job.Size = New Size(462, 22)
                    STRING1TextBoxFile_Job.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Right
                    STRING2TextBoxProfil_FileJob.Size = New Size(543, 22)
                    STRING2TextBoxProfil_FileJob.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Right
                Case 4 'MSSQL
                    btnTestCon.Visible = True
                    lblString1FileJobs.Text = "Connection String MSSQL"
                    lblString2FileJobs.Text = "Command MSSQL"
                    STRING1TextBoxFile_Job.Visible = True
                    STRING2TextBoxProfil_FileJob.Visible = True
                    lblString2FileJobs.Visible = True

            End Select

        End If
    End Sub
    Sub Renamewithindex()
        lblString1FileJobs.Text = "Namenkonvention"
        STRING1ComboBox.Visible = False
        STRING1TextBoxFile_Job.Visible = True
        lblndexname.Visible = True

        cmbFileJob_WHIndexe.Visible = True
        btnFileJob_addIndex.Visible = True
    End Sub


    Private Sub tabtn_refreshProfile_Click(sender As Object, e As EventArgs) Handles tabtn_refreshProfile.Click
        Load_Profil()
    End Sub

    Private Sub tsbtmrefresh_Uebersicht_Click(sender As Object, e As EventArgs) Handles tsbtmrefresh_Uebersicht.Click
        Load_Uebersicht()
    End Sub

    Private Sub btnsave_Grundkonfig_Click(sender As Object, e As EventArgs) Handles btnsave_Grundkonfig.Click
        Try
            Me.TBWMRH_KONFIGURATIONBindingSource.EndEdit()
            If MyDataset.TBWMRH_KONFIGURATION.GetChanges Is Nothing = False Then
                Me.GEAENDERT_WERTextBox.Text = Environment.UserName
                Me.TBWMRH_KONFIGURATIONBindingSource.EndEdit()
                Me.TBWMRH_KONFIGURATIONTableAdapter.Update(MyDataset.TBWMRH_KONFIGURATION)
                statuslabel(True, "Grundkonfiguration gespeichert - " & Now)
                Load_Grundkonfig()
                If LOG_ERRORS_ONLYCheckBox.Checked = False Then
                    MyLogger.Debug = True
                Else
                    MyLogger.Debug = False
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Save Grundkonfig:")
        End Try
    End Sub

    Private Sub btnaddDatetime_Click(sender As Object, e As EventArgs) Handles btnaddDatetime.Click
        Me.STRING2TextBoxProfil_FileJob.Text = STRING2TextBoxProfil_FileJob.Text & "[%DATETIME]"
    End Sub
    Private Sub btnFileJob_addIndex_Click(sender As Object, e As EventArgs) Handles btnFileJob_addIndex.Click
        If cmbFileJob_WHIndexe.SelectedIndex <> -1 Then
            STRING1TextBoxFile_Job.Text = STRING1TextBoxFile_Job.Text & "[%" & cmbFileJob_WHIndexe.Text & "]"
        End If
    End Sub
    Sub Manual(ID As Integer)
        Try
            Dim notcompleted As Boolean = False
            Logger.Info("## Start Durchlauf WindreamResultHandler - " & Now & " ## ")
            _profil = New clsProfil(MyLogger, ID)
            'windream initialisieren
            If _database.Init(My.Settings.SQLSERVER_CS, True) = True Then
                Dim DT As DataTable = _database.Return_Datatable("select * from TBWMRH_KONFIGURATION where GUID = 1")
                If DT.Rows.Count = 1 Then
                    clsCURRENT.DT_TBWMRH_KONFIGURATION = DT
                    clsCURRENT.WDLAUFWERK = clsCURRENT.DT_TBWMRH_KONFIGURATION.Rows(0).Item("WD_LAUFWERK")
                    DD_WMResulthandler.clsCURRENT.LogErrorsOnly = DT.Rows(0).Item("LOG_ERRORS_ONLY")
                    'MyLogger.Debug = DT.Rows(0).Item("LOG_ERRORS_ONLY")
                    If DD_WMResulthandler.clsCURRENT.LogErrorsOnly = False Then
                        Logger.Debug("Detaillog is ON!")
                    End If
                    DD_WMResulthandler.clsCURRENT.WDLAUFWERK = DT.Rows(0).Item("WD_LAUFWERK")
                End If

                If _windream.Init() = True Then
                    Logger.Info("windream vollumfänglich initialisiert!")
                    DT = _database.Return_Datatable("SELECT GUID FROM TBWMRH_PROFIL WHERE GUID = " & ID)
                    If DT.Rows.Count > 0 Then
                        Logger.Info("Anzahl der aktiven Profile: " & DT.Rows.Count.ToString)
                        For Each DR As DataRow In DT.Rows
                            clsCURRENT._PROFIL_ID = CInt(DR.Item("GUID"))
                            'Und nun das Profil durchlaufen
                            Dim initresult = _profil.Init(clsCURRENT._PROFIL_ID, True)
                            If initresult = True Then
                                _profil.Profil_Durchlauf(True)
                            ElseIf initresult = False Then
                                Logger.Warn("clsProfil konnte nicht initialisiert werden")
                                notcompleted = True
                            ElseIf initresult = 0 Then
                                Logger.Warn("initresult: 0")
                                notcompleted = True
                            ElseIf initresult = 1 Then
                                Logger.Warn("initresult: 1")
                                notcompleted = True
                            End If
                        Next
                    Else
                        Logger.Warn("- Keine aktiven Profile vorhanden")
                        notcompleted = True
                    End If
                Else
                    Logger.Warn("# Achtung: Windream-Init mit Fehlern beendet")
                End If
                _database.Execute_non_Query("UPDATE TBWMRH_KONFIGURATION SET LAST_TICK = GETDATE() WHERE GUID = 1")
            Else
                Logger.Warn("- clsDatatabase konnte nicht initialisiert werden!")
                notcompleted = True
            End If

            If notcompleted = True Then
                MsgBox("Run completed with errors - Check the log!", MsgBoxStyle.Information)
            Else
                MsgBox("Run completed!", MsgBoxStyle.Information)
            End If

        Catch ex As Exception
            Logger.Error(ex)

        End Try
    End Sub

    Private Sub TBWMRH_PROFIL_JOBBindingSource_AddingNew_1(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBWMRH_PROFIL_JOBBindingSource.AddingNew
        MyDataset.TBWMRH_PROFIL_JOB.ERSTELLTWERColumn.DefaultValue = Environment.UserName
        MyDataset.TBWMRH_PROFIL_JOB.PROFIL_IDColumn.DefaultValue = GUIDTextBox.Text
    End Sub

    Private Sub TBWMRH_PROFIL_FILE_JOBBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBWMRH_PROFIL_FILE_JOBBindingSource.AddingNew
        MyDataset.TBWMRH_PROFIL_FILE_JOB.ERSTELLTWERColumn.DefaultValue = Environment.UserName
        MyDataset.TBWMRH_PROFIL_FILE_JOB.PROFIL_IDColumn.DefaultValue = GUIDTextBox.Text

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Try
            Process.Start(MyLogger.LogFile)
        Catch ex As Exception
            MsgBox(ex.Message & vbNewLine & "Logfile: " & MyLogger.LogFile)
        End Try

    End Sub

    Private Sub btnTestCon_Click(sender As Object, e As EventArgs) Handles btnTestCon.Click
        If STRING1TextBoxFile_Job.Text = "" Then
            Exit Sub
        End If
        If STEP_TYPComboBox.Text = "Execute Oracle Command" Then
            If _database.Oracle_CS_Test(STRING1TextBoxFile_Job.Text) = True Then
                MsgBox("Oracle Connection successfull!", MsgBoxStyle.Information)
                Exit Sub
            End If
        ElseIf STEP_TYPComboBox.Text = "Execute MSSQL Command" Then
            If _database.MSSQL_CS_Test(STRING1TextBoxFile_Job.Text) = True Then
                MsgBox("MSSQL Connection successfull!", MsgBoxStyle.Information)
                Exit Sub
            End If
        End If
        MsgBox("Connection could not be created - Check the log", MsgBoxStyle.Critical)


    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            Dim p As New Process()
            p.StartInfo.FileName = Me.WindreamSucheTextBox.Text
            p.StartInfo.WindowStyle = ProcessWindowStyle.Normal
            p.Start()
            p.WaitForExit()
            p.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Öffnen der windream-Suche:")
        End Try
    End Sub

    Private Sub TBWMRH_PROFIL_JOBBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBWMRH_PROFIL_JOBBindingSource.CurrentChanged
        If IsNumeric(PROFILJOB_GUIDTextBox.Text) Then
            Show_String_Lables()
        End If
    End Sub

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

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

    Private Sub ToolStripButton15_Click(sender As Object, e As EventArgs) Handles ToolStripButton15.Click
        TBDD_EMAIL_ACCOUNTBindingSource.AddNew()
    End Sub

    Private Sub ToolStripButton21_Click(sender As Object, e As EventArgs) Handles ToolStripButton21.Click
        SaveEmail()
    End Sub
    Sub SaveEmail()
        Try
            Me.TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
            If MyDataset.TBDD_EMAIL_ACCOUNT.GetChanges Is Nothing = False Then
                Me.GEAENDERT_WERTextBox.Text = Environment.UserName
                Me.TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
                Me.TBDD_EMAIL_ACCOUNTTableAdapter.Update(MyDataset.TBDD_EMAIL_ACCOUNT)
                statuslabel(True, "Email-Data gespeichert - " & Now)

            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Save Email:")
        End Try
    End Sub
    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Try
            My.Settings.Save()
            Dim wrapper As New clsEncryption("!35452didalog=")

            Dim PWPlain = wrapper.DecryptData(EMAIL_PWTextBox.Text)
            Dim sClient = New SmtpClient(EMAIL_SMTPTextBox.Text)
            Dim mymesssage As New MailMessage
            sClient.Port = PORTTextBox.Text
            If AUTH_TYPEComboBox.Text = "SSL" Then
                sClient.EnableSsl = True
            Else
                sClient.EnableSsl = False
            End If

            sClient.Credentials = New NetworkCredential(EMAIL_USERTextBox.Text, PWPlain)
            sClient.UseDefaultCredentials = False

            mymesssage.Body = $"This is the body (text will be replaced within profile)! <br> mailsmtp: {EMAIL_SMTPTextBox.Text} <br> mailport: {PORTTextBox.Text} <br> mailUser: {EMAIL_USERTextBox.Text} <br> mailPW: XXXX <br> AUTH_TYPE: {AUTH_TYPEComboBox.Text}"
            Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(mymesssage.Body)
            htmlView.ContentType = New System.Net.Mime.ContentType("text/html")
            mymesssage.AlternateViews.Add(htmlView)

            mymesssage.From = New MailAddress(EMAIL_FROMTextBox.Text)
            mymesssage.Subject = "TestSubject from RAW Method"
            mymesssage.To.Add(New MailAddress(txtTestmailTo.Text))

            If txtAttachment.Text <> String.Empty Then
                Dim oAttment As String = txtAttachment.Text.Replace("W:\", "\\windream\objects\")

                If System.IO.File.Exists(oAttment) Then
                    Logger.Info($"working on attachment {oAttment}...")
                    Dim oAttachment As New System.Net.Mail.Attachment(oAttment)

                    mymesssage.Attachments.Add(oAttachment)
                Else
                    MsgBox($"Attachment {oAttment.ToString} is not existing - Mail won't be send!")
                    Exit Sub
                End If
            End If


            sClient.Send(mymesssage)
            MsgBox("Email has been sent!")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub
    Private Sub btnsendtestmail_Click(sender As Object, e As EventArgs) Handles btnsendtestmail.Click
        '   Dim _ss2email As New Email(MyLogger)
        Dim oSender As New MailSender(MyLogger)

        If txtTestmailTo.Text <> String.Empty Then
            My.Settings.Save()
            Dim wrapper As New clsEncryption("!35452didalog=")

            Dim PWPlain = wrapper.DecryptData(EMAIL_PWTextBox.Text)
            Dim oSession = oSender.Connect(EMAIL_SMTPTextBox.Text, PORTTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text)
            If oSession.Connected = True Then
                Dim oSendto As New List(Of String)
                oSendto.Add(txtTestmailTo.Text)
                Dim oAttMt As New List(Of String)
                If txtAttachment.Text <> String.Empty Then
                    oAttMt.Add(txtAttachment.Text)
                End If
                If oSender.SendMail(oSendto, EMAIL_FROMTextBox.Text, "Testmail from GUI WMResultHandler", "TEST", Now, oAttMt, 1) = True Then
                    MsgBox("Email has been sent successfully.", MsgBoxStyle.Information)
                Else
                    MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
                End If
                oSender.Disconnect()
            Else
                MsgBox("Could not connect to server. Please check the log.", MsgBoxStyle.Exclamation)

            End If
            ' Dim oSMTP As SmtpClient = llmail.New_SMTPConnection(Nothing, EMAIL_SMTPTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text, PORTTextBox.Text)
            'If _ss2email.NewEmail(txtTestmailTo.Text, "Testmail from GUI WMResultHandler", "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 WMRH - Test") = True Then
            '        MsgBox("Email(s) has/have been sent successfully.", MsgBoxStyle.Information)
            '    Else
            '        MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
            '    End If
        End If

    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim wrapper As New clsEncryption("!35452didalog=")
        Dim pwencrypted = wrapper.EncryptData(txtnewpasswort.Text)
        EMAIL_PWTextBox.Text = pwencrypted
        SaveEmail()
        MsgBox("Passwort was encrypted!")
    End Sub

    Private Sub ToolStripButton22_Click(sender As Object, e As EventArgs) Handles ToolStripButton22.Click
        load_Emails()
    End Sub


    Private Sub btnlookupPDFTK_Click(sender As Object, e As EventArgs) Handles btnlookupPDFTK.Click
        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            PDF_TK_LOCATIONTextBox.Text = OpenFileDialog1.FileName

        End If
    End Sub

    Private Sub btnlookupPDFXCHANGE_Click(sender As Object, e As EventArgs) Handles btnlookupPDFXCHANGE.Click
        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            PDF_XCHANGE_LOCATIONTextBox.Text = OpenFileDialog1.FileName
        End If
    End Sub

    Private Sub ToolStripButton23_Click(sender As Object, e As EventArgs) Handles tsbtnStartProfile.Click
        Try
            If IsNumeric(Me.GUIDTextBox.Text) Then
                Me.TBWMRH_PROFILTableAdapter.cmdUpdateRunningnow(Me.GUIDTextBox.Text)
                Manual(Me.GUIDTextBox.Text)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles TabPage2.Click

    End Sub

    Private Sub ToolStripButton23_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton23.Click
        Load_Jobs(GUIDTextBox.Text)
    End Sub

    Private Sub ToolStripButton24_Click(sender As Object, e As EventArgs) Handles ToolStripButton24.Click
        Load_FILE_JOBS(GUIDTextBox.Text)
    End Sub

    Private Sub NumericUpDown_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown.ValueChanged
        Select Case cmbTimeTyp.SelectedValue
            Case "Intervall"
                Me.dtp_Time.Visible = False
                Me.NumericUpDown.Visible = True
                RunTextBox.Text = "INTV;" & NumericUpDown.Value
            Case "Uhrzeit"
                Me.dtp_Time.Visible = True
                Me.NumericUpDown.Visible = False
                RunTextBox.Text = "TIME;" & dtp_Time.Text
        End Select
    End Sub

    Private Sub dtp_Time_ValueChanged(sender As Object, e As EventArgs) Handles dtp_Time.ValueChanged
        Select Case cmbTimeTyp.SelectedValue
            Case "Uhrzeit"
                Me.NumericUpDown.Visible = False
                Me.dtp_Time.Visible = True
                RunTextBox.Text = "TIME;" & dtp_Time.Text
        End Select
    End Sub

    Private Sub EncryptToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EncryptToolStripMenuItem.Click
        Dim wrapper As New clsEncryption("!35452didalog=")
        Dim pwencrypted = wrapper.DecryptData(EMAIL_PWTextBox.Text)
        MsgBox("PW is: " & pwencrypted)
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Dim Dayofweek As Integer = My.Computer.Clock.LocalTime.DayOfWeek
        Dim SUBS As Integer = 0
        Dim RUNTODAY As Integer = 0
        Select Case Dayofweek
            Case 6 'Saturday
            Case 5 'Friday
            Case 4 'Thursday
            Case 3 'Wednesday
            Case 2 'Tuesday
            Case 1 'Monday
            Case 0 'Sunday
        End Select
        If Dayofweek = 0 Then
            SUBS = 6
        Else
            SUBS = Dayofweek - 1
        End If
        RUNTODAY = TextBox1.Text.Substring(SUBS, 1)
        MsgBox(RUNTODAY)
    End Sub

    Private Sub LOG_ERRORS_ONLYCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LOG_ERRORS_ONLYCheckBox.CheckedChanged
        My.Settings.Debug_Active = LOG_ERRORS_ONLYCheckBox.Checked
        My.Settings.Save()
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim oFD As OpenFileDialog = New OpenFileDialog()

        oFD.Title = "Get a test-attachment:"
        'oFD.InitialDirectory = "C:\"
        oFD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        oFD.FilterIndex = 2
        oFD.RestoreDirectory = True

        If oFD.ShowDialog() = DialogResult.OK Then
            txtAttachment.Text = oFD.FileName
        End If
    End Sub
End Class
