Imports System.Text.RegularExpressions
Imports DevExpress.XtraLayout
Imports DigitalData.GUIs.Common
Imports DigitalData.Modules.Logging

Public Class frmAdmin_Globix
    Implements IAdminForm
    Public Property HasChanges As Boolean = False Implements IAdminForm.HasChanges
    Public Property IsInsert As Boolean = False Implements IAdminForm.IsInsert
    Public Property PrimaryKey As Integer Implements IAdminForm.PrimaryKey
    Public Property GlobixHelper As ClassGIDatatables

    Private AttributesManual As new Dictionary(Of String, String)
    Private AttributesAutomatic As New Dictionary(Of String, String)

    Private Pages As ClassDetailPageManager
    Private Logger As Logger = My.LogConfig.GetLogger
    Private FormHelper As FormHelper

    Public Sub New(PrimaryKey As Integer, Optional IsInsert As Boolean = False)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Me.PrimaryKey = PrimaryKey
        Me.IsInsert = IsInsert
        Me.GlobixHelper = New ClassGIDatatables(My.LogConfig)
        FormHelper = New FormHelper(My.LogConfig, Me)
    End Sub

    Private Sub frmAdmin_Globix_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            VWIDB_DOCTYPE_LANGUAGETableAdapter.Connection.ConnectionString = My.DatabaseIDB.CurrentSQLConnectionString
            TBDD_DOKUMENTARTTableAdapter.Connection.ConnectionString = My.DatabaseECM.CurrentSQLConnectionString
            TBGI_REGEX_DOCTYPETableAdapter.Connection.ConnectionString = My.DatabaseECM.CurrentSQLConnectionString
            VWIDB_OBJECT_STORETableAdapter.Connection.ConnectionString = My.DatabaseIDB.CurrentSQLConnectionString
            VWIDB_BE_ATTRIBUTETableAdapter.Connection.ConnectionString = My.DatabaseIDB.CurrentSQLConnectionString
            TBDD_INDEX_MANTableAdapter.Connection.ConnectionString = My.DatabaseECM.CurrentSQLConnectionString

            Me.VWIDB_DOCTYPE_LANGUAGETableAdapter.FillByLanguage(Me.DSIDB_Stammdaten.VWIDB_DOCTYPE_LANGUAGE, My.Application.User.Language)
            TBDD_DOKUMENTARTTableAdapter.Fill(Me.GlobixDataset.TBDD_DOKUMENTART, PrimaryKey)
            Me.VWIDB_OBJECT_STORETableAdapter.Fill(Me.DSIDB_Stammdaten.VWIDB_OBJECT_STORE)

            Try
                Me.VWIDB_BE_ATTRIBUTETableAdapter.Fill(Me.DSIDB_Stammdaten.VWIDB_BE_ATTRIBUTE, My.Application.User.Language)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error loading VWIDB_BE_ATTRIBUTE")
            End Try

            Load_TabData()

            ' Add Focus Handler to all controls in all LayoutControls
            Dim oLayoutControls = New List(Of LayoutControl) From {LayoutControlProfile, LayoutControlManIndexe, LayoutControlAutoIndexe, LayoutControlRework}
            Pages = New ClassDetailPageManager(My.LogConfig, Me, oLayoutControls)
            Pages.AddRange({
                New ClassDetailPageManager.PrimaryPage(IsInsert) With {
                    .Name = "Profile Globix",
                    .TabPage = XtraTabPageProfile,
                    .BindingSource = TBDD_DOKUMENTARTBindingSource,
                    .DataTable = GlobixDataset.TBDD_DOKUMENTART,
                    .AddedWhoEdit = TextEditErstelltWer,
                    .ChangedWhoEdit = TextEditGeandertWer
                },
                New ClassDetailPageManager.DetailPage With {
                    .Name = "Manual Attributes",
                    .TabPage = XtraTabPageManIndexe,
                    .BindingSource = TBDD_INDEX_MANBindingSource,
                    .DataTable = GlobixDataset.TBDD_INDEX_MAN,
                    .AddedWhoEdit = TextEditAddedWho_ManIndex,
                    .ChangedWhoEdit = TextEditChangedWho_ManIndex
                },
                 New ClassDetailPageManager.DetailPage With {
                    .Name = "Auto Attributes",
                    .TabPage = XtraTabPageAutoIndexe,
                    .BindingSource = TBDD_INDEX_AUTOMBindingSource,
                    .DataTable = GlobixDataset.TBDD_INDEX_AUTOM,
                    .AddedWhoEdit = ADDED_WHOTextBoxAutoAttribut,
                    .ChangedWhoEdit = CHANGED_WHOTextEditAutoAttribut
                },
                 New ClassDetailPageManager.DetailPage With {
                    .Name = "Auto Attributes",
                    .TabPage = XtraTabPageAutoSelect,
                    .BindingSource = TBGI_REGEX_DOCTYPEBindingSource,
                    .DataTable = GlobixDataset.TBGI_REGEX_DOCTYPE,
                    .AddedWhoEdit = AddedWhoAutoSelect,
                    .ChangedWhoEdit = ChangedWhoAutoSelect
                },
                 New ClassDetailPageManager.DetailPage With {
                    .Name = "Dynamic Folder",
                    .TabPage = XtraTabPageDynamicFolder,
                    .BindingSource = TBDD_DOKUMENTARTBindingSource,
                    .DataTable = GlobixDataset.TBDD_DOKUMENTART,
                    .AddedWhoEdit = TextEditErstelltWer,
                    .ChangedWhoEdit = TextEditGeandertWer
                }
            })

            Pages.PrepareLoad()
            AddHandler Pages.CurrentPage_Changed, AddressOf CurrentPage_Changed
            If IsInsert Then
                TextEditErstelltWer.EditValue = My.Application.User.UserName
                BarButtonNew.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            Else
                TextEditChangedWho_ManIndex.EditValue = My.Application.User.UserName
                BarButtonNew.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            End If
            Dim oDragDropManager As New ClassDragDrop(My.LogConfig)
            oDragDropManager.AddGridView(viewAssignedGroups)
            oDragDropManager.AddGridView(viewAvailableGroups)
            oDragDropManager.AddGridView(viewAssignedUsers)
            oDragDropManager.AddGridView(viewAvailableUsers)
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "frmAdmin_Globix_Load")
        End Try
    End Sub
    Sub Load_TabData()
        Load_Attributes_Manual()
        Load_Attributes_Auto()
    End Sub
    Private Sub Load_Attributes_Manual()
        Try
            If Not IsNumeric(PrimaryKey) Then
                Exit Sub
            End If

            TBDD_INDEX_MANTableAdapter.Fill(GlobixDataset.TBDD_INDEX_MAN, PrimaryKey)

            AttributesManual = GlobixDataset.TBDD_INDEX_MAN.Cast(Of DataRow).
                ToDictionary(Of String, String)(Function(row) row.Item("NAME"), Function(row) row.Item("WD_INDEX"))


        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in Load IndexeManuell: ")
        End Try
    End Sub

    Private Sub Load_Attributes_Auto()
        Try
            If Not IsNumeric(PrimaryKey) Then
                Exit Sub
            End If

            TBDD_INDEX_AUTOMTableAdapter.Fill(GlobixDataset.TBDD_INDEX_AUTOM, PrimaryKey)

            AttributesAutomatic = GlobixDataset.TBDD_INDEX_AUTOM.Cast(Of DataRow).
                ToDictionary(Of String, String)(Function(row) row.Item("INDEXNAME"), Function(row) row.Item("INDEXNAME"))

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub


    Private Sub CurrentPage_Changed(sender As Object, e As ClassDetailPageManager.DetailPageEventArgs)
        If Not IsNothing(e.Page) Then
            If e.Page.IsPrimary = True Then
                BarButtonNew.Enabled = False
            Else
                BarButtonNew.Enabled = True
            End If

            RibbonPageGroup1.Text = e.Page.Name
        End If
    End Sub
    Private Sub ResetMessages()
        labelStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        bsiStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
    End Sub

    Private Sub ShowStatus(Message As String, ocolor As Color)
        labelStatus.Caption = Message
        bsiStatus.Caption = $"{Message} - {Now.ToString}"
        bsiStatus.ItemAppearance.Normal.BackColor = ocolor
        bsiStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
    End Sub

    Public Function DeleteData() As Boolean Implements IAdminForm.DeleteData
        Throw New NotImplementedException()
    End Function

    Private Sub BarButtonSave_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonSave.ItemClick
        ResetMessages()

        ' If Pages.PrepareSave() = True Then
        Try
            Dim oPage = Pages.Current

            Select Case oPage.TabPage.Name
                Case XtraTabPageProfile.Name
                    If IsInsert Then
                        Insert_Doctype()
                    Else
                        Update_Doctype()
                    End If


                Case XtraTabPageManIndexe.Name
                    Try
                        Save_manIndexe(oPage)
                        Load_Attributes_Manual()
                    Catch ex As Exception

                    End Try
                Case XtraTabPageAutoIndexe.Name
                    Save_AutoIndexe(oPage)
                    Load_Attributes_Auto()
                Case XtraTabPageAutoSelect.Name
                    Save_AutoSelect(oPage)
                Case XtraTabPageDynamicFolder.Name
                    Update_Doctype()
            End Select

            oPage.IsInsert = False

            ShowStatus($"{oPage.Name} saved - {Now.ToString}", Color.DodgerBlue)
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "BarButtonSave_ItemClick")
            ShowStatus($"{ex.Message} saved - {Now.ToString}", Color.Red)
        End Try
        'Else
        '    ShowStatus("Keine Änderungen!")
        'End If
    End Sub
    Private Function Save_manIndexe(oPage As ClassDetailPageManager.DetailPage) As Boolean
        Try
            TBDD_INDEX_MANBindingSource.EndEdit()
            If GlobixDataset.TBDD_INDEX_MAN.GetChanges() IsNot Nothing Then
                If Pages.Current.IsInsert Then
                    TextEditAddedWho_ManIndex.Text = My.Application.User.UserName
                Else
                    TextEditChangedWho_ManIndex.Text = My.Application.User.UserName
                End If
                TBDD_INDEX_MANBindingSource.EndEdit()
                TBDD_INDEX_MANTableAdapter.Update(Pages.Current.DataTable)
            End If

            ShowStatus("Manual Attribut-Step saved", Color.DodgerBlue)
            Return True
        Catch ex As Exception
            ShowStatus($"Error saving ManIndex {ex.Message} - {Now.ToString}", Color.Red)
            Return False
        End Try
    End Function
    Private Function Save_AutoIndexe(oPage As ClassDetailPageManager.DetailPage) As Boolean
        Try
            TBDD_INDEX_AUTOMBindingSource.EndEdit()
            If GlobixDataset.TBDD_INDEX_AUTOM.GetChanges() IsNot Nothing Then
                If Pages.Current.IsInsert Then
                    TextEditAddedWho_ManIndex.Text = My.Application.User.UserName
                Else
                    TextEditChangedWho_ManIndex.Text = My.Application.User.UserName
                End If
                TBDD_INDEX_AUTOMBindingSource.EndEdit()
                TBDD_INDEX_AUTOMTableAdapter.Update(Pages.Current.DataTable)
                ShowStatus($"Auto Attribut-Step saved", Color.DodgerBlue)

            End If
            Return True
        Catch ex As Exception
            Return False
            ShowStatus($"Error saving AutoIndex - {ex.Message}", Color.Red)

        End Try
    End Function
    Private Function Save_AutoSelect(oPage As ClassDetailPageManager.DetailPage) As Boolean
        Try
            TBGI_REGEX_DOCTYPEBindingSource.EndEdit()
            If GlobixDataset.TBGI_REGEX_DOCTYPE.GetChanges() IsNot Nothing Then
                If Pages.Current.IsInsert Then
                    AddedWhoAutoSelect.Text = My.Application.User.UserName
                Else
                    ChangedWhoAutoSelect.Text = My.Application.User.UserName
                End If
                TBGI_REGEX_DOCTYPEBindingSource.EndEdit()
                TBGI_REGEX_DOCTYPETableAdapter.Update(Pages.Current.DataTable)

                ShowStatus($"Autoselect saved", Color.DodgerBlue)
            End If
            Return True
        Catch ex As Exception
            ShowStatus($"Error saving autoselect - {ex.Message}", Color.Red)
            Return False
        End Try
    End Function
    Private Function Insert_Doctype() As Boolean
        Try
            Dim oIns = $"INSERT INTO [TBDD_DOKUMENTART] ([BEZEICHNUNG] ,[OBJEKTTYP] ,[EINGANGSART_ID] ,[IDB_DOCTYPE_ID] ,[ZIEL_PFAD] ,[BESCHREIBUNG]
                                    ,[WINDREAM_DIRECT] ,[FOLDER_FOR_INDEX] ,[DUPLICATE_HANDLING],[AKTIV],[LANGUAGE],
                                    [SEQUENCE],[NAMENKONVENTION],[ERSTELLTWER],IDB_OBJECT_STORE_ID,KURZNAME)     VALUES 
                                    ('{TextEditBezeichnung.Text}','IDB_DRIVEN',1,{IDB_DOCTYPE_IDComboBox.SelectedValue},'IDB_STORE','{TextEditBeschreibung.Text}'
                                    ,'False','{FOLDER_FOR_INDEXTextEdit.Text}','{ComboBoxEditDupl_handling.EditValue}' ,'{CheckEdit1.Checked}','{My.Application.User.Language}'
                                    , {SEQUENCENumericUpDown.Value},'{TextEditNamenkonvention.Text}','{My.Application.User.UserName}',{IDB_OBJECT_STORE_IDComboBox.SelectedValue},'')"
            If My.DatabaseECM.ExecuteNonQuery(oIns) = True Then
                Dim oSQL = $"SELECT GUID FROM TBDD_DOKUMENTART WHERE BEZEICHNUNG = '{TextEditBezeichnung.Text}'"
                PrimaryKey = My.DatabaseECM.GetScalarValue(oSQL)
                oSQL = $"INSERT INTO TBDD_DOKUMENTART_MODULE (DOKART_ID,MODULE_ID) VALUES ({PrimaryKey},(SELECT GUID FROM TBDD_MODULES WHERE SHORT_NAME = 'GLOBIX'))"
                My.DatabaseECM.ExecuteNonQuery(oSQL)
                IsInsert = False
                TBDD_DOKUMENTARTTableAdapter.Fill(Me.GlobixDataset.TBDD_DOKUMENTART, PrimaryKey)
                ShowStatus($"New FileFlow Profile {TextEditBezeichnung.Text} saved", Color.DodgerBlue)
                Return True
            Else
                ShowStatus("Error Saving Fileflow Profile - Check the Log for further info", Color.Red)
                Return False
            End If
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "Insert_Doctype")
            ShowStatus($"Error Saving Fileflow Profile {ex.Message}", Color.Red)
            Return False
        End Try

    End Function
    Private Function Update_Doctype() As Boolean
        Try
            Dim oUpd = $"UPDATE TBDD_DOKUMENTART SET [BEZEICHNUNG] = '{TextEditBezeichnung.Text}' ,[IDB_DOCTYPE_ID] = {IDB_DOCTYPE_IDComboBox.SelectedValue}
              ,[BESCHREIBUNG] = '{TextEditBeschreibung.Text}',[DUPLICATE_HANDLING] = '{ComboBoxEditDupl_handling.EditValue}'
                        ,[AKTIV] = '{CheckEdit1.Checked}',[SEQUENCE] = {SEQUENCENumericUpDown.Value}
                        ,[NAMENKONVENTION] = '{TextEditNamenkonvention.Text}', [FOLDER_FOR_INDEX] = '{FOLDER_FOR_INDEXTextEdit.Text}'
                        ,[GEANDERTWER] = '{My.Application.User.UserName}',IDB_OBJECT_STORE_ID = {IDB_OBJECT_STORE_IDComboBox.SelectedValue} 
                        WHERE GUID = {TextEditDoctypeID.Text}"

            If My.DatabaseECM.ExecuteNonQuery(oUpd) = True Then
                ShowStatus($"FileFlow Profile {TextEditBezeichnung.Text} saved", Color.DodgerBlue)
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "Update_Doctype")
            Return False
        End Try

    End Function
    Private Sub BarButtonNew_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonNew.ItemClick
        Pages.Current.IsInsert = True

        AddData()
    End Sub
    Public Function AddData() As Boolean
        Dim oPage = Pages.Current

        If Pages.Current Is Nothing Then
            Return False
        End If

        If oPage.IsPrimary = False Then
            Select Case oPage.TabPage.Name
                Case XtraTabPageAutoIndexe.Name
                    oPage.DataTable.Columns.Item("DOCTYPE_ID").DefaultValue = PrimaryKey
                Case XtraTabPageAutoSelect.Name
                    oPage.DataTable.Columns.Item("DOCTYPE_ID").DefaultValue = PrimaryKey
                Case Else
                    oPage.DataTable.Columns.Item("DOK_ID").DefaultValue = PrimaryKey
            End Select

            oPage.DataTable.Columns.Item("ADDED_WHO").DefaultValue = My.Application.User.UserName
        End If

        Select Case oPage.TabPage.Name
            Case XtraTabPageProfile.Name
            Case XtraTabPageManIndexe.Name
                TextEditAddedWho_ManIndex.Text = My.Application.User.UserName
            Case XtraTabPageAutoIndexe.Name
                ADDED_WHOTextBoxAutoAttribut.Text = My.Application.User.UserName
            Case XtraTabPageAutoSelect.Name

        End Select

        Dim oNewRecord As DataRowView = oPage.BindingSource.AddNew()

        Return True
    End Function



    Private Sub btneditSQLmanIndex_Click(sender As Object, e As EventArgs) Handles btneditSQLmanIndex.Click
        If Save_manIndexe(Pages.Current) = True Then
            Try
                Dim oSQLbefore = SQL_RESULTTextBox.Text
                Dim oForm2 As New frmSQLEditor(My.LogConfig, My.DatabaseECM) With {
                    .SQLCommand = SQL_RESULTTextBox.Text,
                    .SQLConnection = IIf(CONNECTION_IDTextBox.Text = "", 1, CONNECTION_IDTextBox.Text),
                    .PlaceholdersManual = AttributesManual
                }
                oForm2.ShowDialog()

                If oForm2.DialogResult = DialogResult.OK And oSQLbefore <> oForm2.SQLCommand Then
                    CONNECTION_IDTextBox.Text = oForm2.SQLConnection
                    SQL_RESULTTextBox.Text = oForm2.SQLCommand
                    'TBDD_INDEX_MANTableAdapter.Adapter.UpdateCommand.Parameters("@SQL_RESULT").Value = oForm.SQLCommand
                    'TBDD_INDEX_MANTableAdapter.Adapter.UpdateCommand.Parameters("@CONNECTION_ID").Value = oForm.ConnectionID
                    TextEditChangedWho_ManIndex.Text = My.Application.User.UserName
                End If
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show(ex.Message)
            End Try


        End If
    End Sub

    Private Sub SimpleButtonNameconvention_Click(sender As Object, e As EventArgs) Handles SimpleButtonNameconvention.Click

        Dim oForm As New frmGlobixNameconvention() With {.Nameconvention = TextEditNamenkonvention.Text, .DoctypeID = TextEditDoctypeID.Text}
        Dim oResult = oForm.ShowDialog()
        TextEditNamenkonvention.Text = oForm.Nameconvention
    End Sub


    Private Sub Load_AutoSelect()
        Try
            Me.TBGI_REGEX_DOCTYPETableAdapter.Fill(Me.GlobixDataset.TBGI_REGEX_DOCTYPE, TextEditDoctypeID.Text)
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try

    End Sub
    Private Sub XtraTabControl2_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl2.SelectedPageChanged
        Dim oPage = Pages.GetDetailPage(e.Page)

        If oPage IsNot Nothing Then
            Pages.Current = oPage
            Select Case oPage.TabPage.Name
                Case XtraTabPageAutoIndexe.Name
                    Load_Attributes_Auto()
                Case XtraTabPageManIndexe.Name
                    Load_Attributes_Manual()
                Case XtraTabPageAutoSelect.Name
                    Load_AutoSelect()
                Case XtraTabPageDynamicFolder.Name
                    cmbAllAttributes.Items.Clear()
                    For Each oRowMan As DataRow In Me.GlobixDataset.TBDD_INDEX_MAN.Rows
                        cmbAllAttributes.Items.Add(oRowMan.Item("WD_INDEX") + " - M")
                    Next
                    For Each oRowMan As DataRow In Me.GlobixDataset.TBDD_INDEX_AUTOM.Rows
                        cmbAllAttributes.Items.Add(oRowMan.Item("INDEXNAME") + " - A")
                    Next
            End Select
            'Else
            '    If XtraTabControl2.SelectedTabPageIndex = 3 Then
            '        sd
            '    End If
        End If


    End Sub

    Private Sub SimpleButton2_Click_1(sender As Object, e As EventArgs) Handles SimpleButton2.Click
        If Save_AutoIndexe(Pages.Current) = True Then
            Dim oSQLbefore = SQL_RESULTTextBox1.Text
            Dim oForm2 As New frmSQLEditor(My.LogConfig, My.DatabaseECM) With {
                .SQLCommand = SQL_RESULTTextBox1.Text,
                .SQLConnection = IIf(CONNECTION_IDTextBox1.Text = "", 1, CONNECTION_IDTextBox1.Text),
                .PlaceholdersAutomatic = AttributesAutomatic,
                .PlaceholdersManual = AttributesManual
            }
            oForm2.ShowDialog()

            If oForm2.DialogResult = DialogResult.OK And oSQLbefore <> oForm2.SQLCommand Then
                CONNECTION_IDTextBox1.Text = oForm2.SQLConnection
                SQL_RESULTTextBox1.Text = oForm2.SQLCommand
                SQL_ACTIVECheckBox.Checked = 1
                CHANGED_WHOTextEditAutoAttribut.Text = My.Application.User.UserName
            End If
        End If
    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 1
                gridAssignedGroups.DataSource = GlobixHelper.GetAssignedGroups(TextEditDoctypeID.Text)
                gridAvailableGroups.DataSource = GlobixHelper.GetAvailableGroups(TextEditDoctypeID.Text)
                gridAssignedUsers.DataSource = GlobixHelper.GetAssignedUsers(TextEditDoctypeID.Text)
                gridAvailableUsers.DataSource = GlobixHelper.GetAvailableUsers(TextEditDoctypeID.Text)
        End Select
    End Sub

    Private Sub gridAssignedUsers_DragDrop(sender As Object, e As DragEventArgs) Handles gridAssignedUsers.DragDrop
        Try
            Dim data As String = e.Data.GetData(DataFormats.Text)
            Dim userId As Integer = data.Split("|")(0)
            Dim profileId As Integer = TextEditDoctypeID.Text

            GlobixHelper.AddUserToProfile(userId, profileId)
            gridAssignedUsers.DataSource = GlobixHelper.GetAssignedUsers(profileId)
            gridAvailableUsers.DataSource = GlobixHelper.GetAvailableUsers(profileId)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Hinzufügen eines Users:")
        End Try
    End Sub

    Private Sub gridAvailableUsers_DragDrop(sender As Object, e As DragEventArgs) Handles gridAvailableUsers.DragDrop
        Try
            Dim data As String = e.Data.GetData(DataFormats.Text)
            Dim userId As Integer = data.Split("|")(0)
            Dim profileId As Integer = TextEditDoctypeID.Text

            GlobixHelper.RemoveUserFromProfile(userId, profileId)
            gridAssignedUsers.DataSource = GlobixHelper.GetAssignedUsers(profileId)
            gridAvailableUsers.DataSource = GlobixHelper.GetAvailableUsers(profileId)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Hinzufügen eines Users:")
        End Try
    End Sub

    Private Sub gridAssignedGroups_DragDrop(sender As Object, e As DragEventArgs) Handles gridAssignedGroups.DragDrop
        Try
            Dim data As String = e.Data.GetData(DataFormats.Text)
            Dim groupId As Integer = data.Split("|")(0)
            Dim profileId As Integer = TextEditDoctypeID.Text

            GlobixHelper.AddGroupToProfile(groupId, profileId)
            gridAssignedGroups.DataSource = GlobixHelper.GetAssignedGroups(profileId)
            gridAvailableGroups.DataSource = GlobixHelper.GetAvailableGroups(profileId)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Hinzufügen einer Gruppe:")
        End Try
    End Sub

    Private Sub gridAvailableGroups_DragDrop(sender As Object, e As DragEventArgs) Handles gridAvailableGroups.DragDrop
        Try
            Dim data As String = e.Data.GetData(DataFormats.Text)
            Dim groupId As Integer = data.Split("|")(0)
            Dim profileId As Integer = TextEditDoctypeID.Text

            GlobixHelper.RemoveGroupFromProfile(groupId, profileId)
            gridAssignedGroups.DataSource = GlobixHelper.GetAssignedGroups(profileId)
            gridAvailableGroups.DataSource = GlobixHelper.GetAvailableGroups(profileId)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Hinzufügen einer Gruppe:")
        End Try
    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        If Not ComboBoxEditAAttrFileParam.SelectedItem Is Nothing Then
            If GUIDTextBoxAutoAttribute.Text <> "" Then
                Dim value As String
                Dim oPattern = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_FILE, ComboBoxEditAAttrFileParam.Text)
                'Select Case ComboBoxEditAAttrFileParam.SelectedIndex
                '    Case 0 : value = "$filename_ext"
                '    Case 1 : value = "$filename"
                '    Case 2 : value = "$extension"
                '    Case 3 : value = "$FileCreateDate"
                '    Case 4 : value = "$FileCreatedWho"
                '    Case 5 : value = "$DateDDMMYYY"
                '    Case 6 : value = "$Username"
                '    Case 7 : value = "$Usercode"
                'End Select


                VALUETextBox.Text = oPattern

            End If
        End If
    End Sub

    Private Sub SimpleButton3_Click(sender As Object, e As EventArgs) Handles SimpleButton3.Click
        Dim str As String
        If (FOLDER_FOR_INDEXTextEdit.Text = "") = False Then
            str = FOLDER_FOR_INDEXTextEdit.Text & "\"
        End If
        If cmbAllAttributes.SelectedIndex <> -1 Then
            Dim oPattern As String
            If cmbAllAttributes.Text.EndsWith(" - M") Then
                oPattern = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_ATTR_MAN, cmbAllAttributes.Text.Replace(" - M", ""))
            ElseIf cmbAllAttributes.Text.EndsWith(" - A") Then
                oPattern = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_ATTR_AUTO, cmbAllAttributes.Text.Replace(" - A", ""))
            End If
            Me.FOLDER_FOR_INDEXTextEdit.Text = str & oPattern
            cmbAllAttributes.SelectedIndex = -1
        ElseIf cmbCrFolderDate.SelectedIndex <> -1 Then
            Dim oPattern As String = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_INT, cmbCrFolderDate.Text)
            Me.FOLDER_FOR_INDEXTextEdit.Text = str & oPattern
            cmbCrFolderDate.SelectedIndex = -1
        ElseIf txtcrFoldermanuell.Text <> "" Then
            Me.FOLDER_FOR_INDEXTextEdit.Text = str & txtcrFoldermanuell.Text
            txtcrFoldermanuell.Text = ""
        End If
        Dim oPage = Pages.Current
        Save_AutoIndexe(oPage)


    End Sub

    Private Sub SimpleButton4_Click(sender As Object, e As EventArgs) Handles SimpleButton4.Click
        Try
            If Regex.IsMatch(REGEXTextBox.Text, txtDateinameTest.Text) Then
                Dim oResult = FormHelper.ShowInfoMessage("The RegEx resulted in a proper match!", "Testing Regex")
            Else
                Dim oResult = FormHelper.ShowWarningMessage("No Match- There might be an error in the RegEx!", "Testing Regex")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in Testing Regex: ")
        End Try
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemDelete.ItemClick
        ResetMessages()

        Dim result As MsgBoxResult


        Try
            Dim oPage = Pages.Current

            Select Case oPage.TabPage.Name
                Case XtraTabPageProfile.Name
                    If My.Application.User.Language = "de-DE" Then
                        result = MessageBox.Show("Sind Sie sicher dass Sie das ausgewählte Profil löschen wollen?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("Are you sure you want to delete the selected profile?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If

                    If result = MsgBoxResult.Yes Then
                        Dim oSQL = $"EXEC PRDD_GLOBIX_DELETE_DOCTYPE {TextEditDoctypeID.Text}"
                        If My.DatabaseECM.ExecuteNonQuery(oSQL) Then
                            TBDD_DOKUMENTARTTableAdapter.Fill(Me.GlobixDataset.TBDD_DOKUMENTART, PrimaryKey)
                            Load_TabData()
                        End If
                    End If


                Case XtraTabPageManIndexe.Name
                    If My.Application.User.Language = "de-DE" Then
                        result = MessageBox.Show("Sind Sie sicher dass Sie das ausgewählte manuelle Attribut löschen wollen?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("Are you sure you want to delete this manual attribute?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If

                    If result = MsgBoxResult.Yes Then
                        TBDD_INDEX_MANTableAdapter.Delete(GUIDTextBoxMANINDEX.Text)
                        Load_Attributes_Manual()
                    End If

                Case XtraTabPageAutoIndexe.Name
                    If My.Application.User.Language = "de-DE" Then
                        result = MessageBox.Show("Sind Sie sicher dass Sie das ausgewählte automatische Attribut löschen wollen?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("Are you sure you want to delete the selected auto attribute?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If
                    If result = MsgBoxResult.Yes Then
                        TBDD_INDEX_AUTOMTableAdapter.Delete(GUIDTextBoxAutoAttribute.Text)
                        Load_Attributes_Auto()
                    End If

                Case XtraTabPageAutoSelect.Name
                    If My.Application.User.Language = "de-DE" Then
                        result = MessageBox.Show("Sind Sie sicher dass Sie die ausgewählte Regex löschen wollen?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("Are you sure you want to delete the selected regex?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If
                    If result = MsgBoxResult.Yes Then
                        TBGI_REGEX_DOCTYPETableAdapter.Delete(GUIDTextBoxAutoSelect.Text)
                        Load_AutoSelect()
                    End If

            End Select

            oPage.IsInsert = False

            ' ShowStatus($"{oPage.Name} deleted!")
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "BarButtonItem2_ItemClick")
        End Try
    End Sub

    Private Sub SQL_ACTIVECheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles SQL_ACTIVECheckBox.CheckedChanged
        If SQL_ACTIVECheckBox.Checked Then
            VALUETextBox.Text = String.Empty
        Else
            SQL_RESULTTextBox1.Text = String.Empty
        End If
    End Sub

    Private Sub WD_INDEXComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles WD_INDEXComboBox.SelectedIndexChanged
        If WD_INDEXComboBox.SelectedIndex <> -1 Then
            TextEdit10.Text = WD_INDEXComboBox.Text
        End If

    End Sub

    Private Sub FOLDER_FOR_INDEXTextEdit_TextChanged(sender As Object, e As EventArgs) Handles FOLDER_FOR_INDEXTextEdit.TextChanged
        If FOLDER_FOR_INDEXTextEdit.Text <> String.Empty Then
            Dim opath = FOLDER_FOR_INDEXTextEdit.Text
            opath = opath.Replace("\\", "\")
            FOLDER_FOR_INDEXTextEdit.Text = opath
        End If
    End Sub
End Class