Public Class frmUserKonfig
    Private Shared _Instance As frmUserKonfig = Nothing
    Public Shared Function Instance() As frmUserKonfig
        If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
            _Instance = New frmUserKonfig
        End If
        _Instance.BringToFront()
        Return _Instance
    End Function
    Private Sub TBDD_USERBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TBDD_USERBindingNavigatorSaveItem.Click
        Save_User()
    End Sub

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


        Load_User()
        Load_Clients()
    End Sub
    Sub Load_User()
        Try
            Me.TBDD_USERTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_USERTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_USER)

            Me.TBDD_USER_GROUPSTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_USER_GROUPSTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_USER_GROUPS)
            Dim sql = "select GUID, CLIENT_NAME FROM TBDD_CLIENT order by Client_Name"
            Dim DT_CLIENT As DataTable = ClassDatabase.Return_Datatable(sql)
        Catch ex As Exception
            MsgBox("Error in frmUserKonfig_Load:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Clients()
        Try
            Me.TBDD_CLIENTTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_CLIENTTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_CLIENT)
        Catch ex As Exception
            MsgBox("Error in Load Clients:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
       
    End Sub
    Sub Save_Clients()
        Try
            Me.TBDD_CLIENTBindingSource.EndEdit()
            If DD_DMSDataSet.TBDD_CLIENT.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox2.Text = Environment.UserName
                Me.TBDD_CLIENTBindingSource.EndEdit()
                Me.TBDD_CLIENTTableAdapter.Update(Me.DD_DMSDataSet.TBDD_CLIENT)
                Label7.Visible = True
            Else
                Label7.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save Clients:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Sub Save_User()
        Try
            Me.TBDD_USERBindingSource.EndEdit()
            If DD_DMSDataSet.TBDD_USER.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = Environment.UserName
                Me.TBDD_USERBindingSource.EndEdit()
                Me.TBDD_USERTableAdapter.Update(Me.DD_DMSDataSet.TBDD_USER)
                lblsave.Visible = True
            Else
                lblsave.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save USer:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub TBDD_USERBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_USERBindingSource.AddingNew
        DD_DMSDataSet.TBDD_USER.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub tsAddUser_Click(sender As Object, e As EventArgs) Handles tsAddUser.Click
        Dim frm As New frmUserKonfig_AddUsers
        Cursor = Cursors.WaitCursor
        frm.ShowDialog()
        Load_User()
        Cursor = Cursors.Default
    End Sub

    Private Sub tbRefreshUsers_Click(sender As Object, e As EventArgs) Handles tbRefreshUsers.Click
        Load_User()
    End Sub

    Private Sub btnAddUserToGroup_Click(sender As Object, e As EventArgs) Handles btnAddUserToGroup.Click
        Try
            Dim user As DataRowView = GetSelectedUserObject()
            Dim group As DataRowView = GetSelectedGroupObject()

            Dim userID As Integer = user.Item(0)
            Dim userName As String = user.Item(3)

            Dim groupID As Integer = group.Item(0)
            Dim groupName As String = group.Item(1)

            Dim SQL = String.Format("SELECT GUID FROM TBDD_GROUPS_USER WHERE USER_ID = {0} AND GROUP_ID = {1}", userID, groupID)

            Dim userInGroup = ClassDatabase.Execute_Scalar(SQL)

            If Not IsNothing(userInGroup) Then
                MsgBox(String.Format("Der Benutzer {0} ist bereits Mitglied der Gruppe {1}", userName, groupName), MsgBoxStyle.Exclamation)
                Exit Sub
            Else
                SQL = String.Format("INSERT INTO TBDD_GROUPS_USER (USER_ID, GROUP_ID, ADDED_WHO) VALUES ({0}, {1}, '{2}')", userID, groupID, Environment.UserName)
                If ClassDatabase.Execute_non_Query(SQL) = True Then
                    LoadGroupsForSelectedUser()
                Else
                    MsgBox(String.Format("Fehler beim Hinzufügen des Benutzers {0} zur Gruppe {1}", userName, groupName))
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in btnAddUserToGroup_Click:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Function GetSelectedUserObject() As DataRowView
        Dim user As DataRowView = lbUsers.SelectedItem
        Return user
    End Function

    Private Function GetSelectedGroupObject() As DataRowView
        Dim group As DataRowView = cmbGroup.SelectedItem
        Return group
    End Function

    Private Function GetSelectedGroupObjectFromList() As String
        Return lbGroups.SelectedItem
    End Function

    Private Sub LoadGroupsForSelectedUser()
        Dim userID As Integer
        Try
            userID = USER_GUIDTextBox.Text
        Catch ex As Exception
            Exit Sub
        End Try
        Dim SQL As String = String.Format("SELECT GROUP_NAME FROM VWPMO_USERS_GROUPS WHERE USER_ID = {0}", userID)

            Try
                Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL)

                lbGroups.Items.Clear()
                For Each row As DataRow In dt.Rows
                    lbGroups.Items.Add(row.Item(0).ToString)
                Next
            Catch ex As Exception
                MsgBox("Error in LoadGroupsForSelectedUser:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try

    End Sub
    Private Sub GetMandantForSelectedUser()
        Dim userID As Integer
        Try
            userID = USER_GUIDTextBox.Text
        Catch ex As Exception
            Exit Sub
        End Try

        Dim SQL As String = String.Format("SELECT T.GUID, T1.CLIENT_NAME FROM TBDD_CLIENT_USER T, TBDD_CLIENT T1 WHERE T.CLIENT_ID = T1.GUID AND T.USER_ID = {0} ORDEr BY T1.CLIENT_NAME", userID)

        Try
            Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL)

            lstbxUserMandant.Items.Clear()
            For Each row As DataRow In dt.Rows
                lstbxUserMandant.Items.Add(row.Item(1).ToString)
            Next
        Catch ex As Exception
            MsgBox("Error in GetMandantForSelectedUser:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub

    Private Sub TBDD_USERBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBDD_USERBindingSource.PositionChanged
        LoadGroupsForSelectedUser()
        GetMandantForSelectedUser()
    End Sub

    Private Sub btnRemoveUserFromGroup_Click(sender As Object, e As EventArgs) Handles btnRemoveUserFromGroup.Click
        Try
            Dim user As DataRowView = GetSelectedUserObject()
            Dim userID As Integer = user.Item(0)
            Dim userName As String = user.Item(3)
            Dim group As String = GetSelectedGroupObjectFromList()

            ' Gruppen ID über Name auslesen
            Dim SQL = String.Format("SELECT GUID FROM TBDD_USER_GROUPS WHERE NAME = '{0}'", group)
            Dim groupID As Integer = ClassDatabase.Execute_Scalar(SQL)

            ' Keine Gruppe ausgewählt
            If IsNothing(group) Then
                MsgBox("Bitte wählen Sie eine Gruppe aus.", MsgBoxStyle.Exclamation)
                Exit Sub
            End If

            SQL = String.Format("DELETE FROM TBDD_GROUPS_USER WHERE USER_ID = {0} AND GROUP_ID = {1}", userID, groupID)
            If ClassDatabase.Execute_non_Query(SQL) = True Then
                LoadGroupsForSelectedUser()
            Else
                Throw New Exception(String.Format("Fehler beim Löschen der Gruppe {0} für Benutzer {1}", group, userName))
            End If
        Catch ex As Exception
            MsgBox("Error in btnRemoveUserFromGroup_Click:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub TBDD_USER_GROUPSBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_USER_GROUPSBindingSource.AddingNew
        Me.DD_DMSDataSet.TBDD_USER_GROUPS.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
        Save_Groups()
    End Sub

    Sub Save_Groups()
        Try
            Me.TBDD_USER_GROUPSBindingSource.EndEdit()
            If DD_DMSDataSet.TBDD_USER_GROUPS.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox1.Text = Environment.UserName
                Me.TBDD_USER_GROUPSBindingSource.EndEdit()
                Me.TBDD_USER_GROUPSTableAdapter.Update(Me.DD_DMSDataSet.TBDD_USER_GROUPS)
                MsgBox("Changes saved successfully.", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Groups:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton8_Click(sender As Object, e As EventArgs) Handles ToolStripButton8.Click
        Load_Groups()
    End Sub
    Sub Load_Groups()
        Try
            Me.TBDD_USER_GROUPSTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_USER_GROUPS)
        Catch ex As Exception
            MsgBox("Error in Load_Groups:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 0
                Load_Groups()
                LoadGroupsForSelectedUser()
            Case 1
        End Select

    End Sub

    Private Sub LANGUAGEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LANGUAGEComboBox.SelectedIndexChanged

    End Sub

    Private Sub frmUserKonfig_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        GetMandantForSelectedUser()
    End Sub
    Public Class MyListBoxItem
        Private _text As String
        Private _extraData As String

        Public Property Text As String
            Get
                Return _text
            End Get
            Set(ByVal value As String)
                _text = value
            End Set
        End Property

        Public Property ExtraData As String
            Get
                Return _extraData
            End Get
            Set(ByVal value As String)
                _extraData = value
            End Set
        End Property

        Public Overrides Function ToString() As String
            Return Text
        End Function

    End Class
    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Select Case TabControl1.SelectedIndex
            Case 0
                Load_Groups()
                LoadGroupsForSelectedUser()
            Case 1
                Load_Groups()
                clbUsersGroups.Items.Clear()
                Dim sql = String.Format("SELECT DISTINCT T.GUID, T.USERNAME FROM TBDD_USER T where T.GUID in (SELECT DISTINCT USER_ID FROM TBDD_CLIENT_USER WHERE CLIENT_ID IN ({0})) ORDER BY T.USERNAME", USER_CLIENTS_COMMA_SEPERATED)
                Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
                For Each userrow As DataRow In DT.Rows
                    clbUsersGroups.Items.Add(New MyListBoxItem() With {.Text = userrow.Item(1), .ExtraData = userrow.Item(0)})
                Next
                Try
                    cmbGroups_Group2User.SelectedIndex = 1
                Catch ex As Exception

                End Try
                cmbGroups_Group2User.SelectedIndex = 0
        End Select
    End Sub

    Private Sub btnaddSelectedUser2Group_Click(sender As Object, e As EventArgs) Handles btnaddSelectedUser2Group.Click
        For Each obj As Object In clbUsersGroups.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql = "select count(*) from TBDD_GROUPS_USER Where user_id = " & item.ExtraData & " AND GROUP_ID = " & cmbGroups_Group2User.SelectedValue
            If ClassDatabase.Execute_Scalar(sql) = 0 Then
                sql = String.Format("INSERT INTO TBDD_GROUPS_USER (USER_ID, GROUP_ID, ADDED_WHO) VALUES ({0}, {1}, '{2}')", item.ExtraData, cmbGroups_Group2User.SelectedValue, Environment.UserName)
                If ClassDatabase.Execute_non_Query(sql) = False Then
                    MsgBox(String.Format("Error in Adding User {0} to Group {1}", item.Text, cmbGroups_Group2User.Text), MsgBoxStyle.Critical)
                End If
            End If

        Next
        LoadUserForGroups()
    End Sub
    Private Sub LoadUserForGroups()
        Dim groupid
        Try
            groupid = cmbGroups_Group2User.SelectedValue
        Catch ex As Exception
            Exit Sub
        End Try
        If groupid Is Nothing Then Exit Sub
        If Not cmbGroups_Group2User.SelectedValue Is Nothing Then
            Dim SQL As String = String.Format("SELECT T1.GUID, T.USERNAME FROM TBDD_USER T, TBDD_GROUPS_USER T1 WHERE T1.USER_ID = T.GUID AND T1.GROUP_ID = {0} ORDER BY T.USERNAME", cmbGroups_Group2User.SelectedValue)
            lblUserforGroup.Text = "User for Group " & cmbGroups_Group2User.Text
            Try
                Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL)
                chklbxUserForGroup.Items.Clear()
                For Each row As DataRow In dt.Rows
                    chklbxUserForGroup.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
                Next
            Catch ex As Exception
                MsgBox("Error in LoadUserForGroups:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If

    End Sub

    Private Sub cmbGroups_Group2User_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbGroups_Group2User.SelectedIndexChanged
        LoadUserForGroups()
    End Sub

    Private Sub btndeleteUserfromGroup_Click(sender As Object, e As EventArgs) Handles btndeleteUserfromGroup.Click
        For Each obj As Object In chklbxUserForGroup.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql
            sql = String.Format("DELETE FROM TBDD_GROUPS_USER  WHERE GUID = {0}", item.ExtraData)
            If ClassDatabase.Execute_non_Query(sql, True) = False Then
                MsgBox(String.Format("Error in deleting User {0} from Group", item.Text), MsgBoxStyle.Critical)
            End If
        Next
        LoadUserForGroups()
    End Sub

    Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton24.Click
        Load_Clients()
    End Sub

    Private Sub ToolStripButton15_Click(sender As Object, e As EventArgs) Handles ToolStripButton23.Click
        Save_Clients()
    End Sub
    Private Sub TBDD_CLIENTBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_CLIENTBindingSource.AddingNew
        DD_DMSDataSet.TBDD_CLIENT.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TabControl3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl3.SelectedIndexChanged
        Select Case TabControl3.SelectedIndex

            Case 1
                Try
                    chklbxUserClient.Items.Clear()
                    Dim sql = String.Format("SELECT T.GUID, T.USERNAME FROM TBDD_USER T where T.GUID in (SELECT DISTINCT USER_ID FROM TBDD_CLIENT_USER WHERE CLIENT_ID IN ({0})) ORDER BY T.USERNAME", USER_CLIENTS_COMMA_SEPERATED)
                    Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
                    For Each userrow As DataRow In DT.Rows
                        chklbxUserClient.Items.Add(New MyListBoxItem() With {.Text = userrow.Item(1), .ExtraData = userrow.Item(0)})
                    Next
                Catch ex As Exception
                    MsgBox("Error in LoadUserForClients:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End Try
                Try
                    cmbClientsforUser.SelectedIndex = 1
                Catch ex As Exception
                End Try
                cmbClientsforUser.SelectedIndex = 0
        End Select
    End Sub

    Private Sub btnsaddUser2Client_Click(sender As Object, e As EventArgs) Handles btnsaddUser2Client.Click
        For Each obj As Object In chklbxUserClient.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql = "select count(*) from TBDD_CLIENT_USER Where user_id = " & item.ExtraData & " AND CLIENT_ID = " & cmbClientsforUser.SelectedValue
            If ClassDatabase.Execute_Scalar(sql) = 0 Then
                sql = String.Format("INSERT INTO TBDD_CLIENT_USER (USER_ID, CLIENT_ID, ADDED_WHO) VALUES ({0}, {1}, '{2}')", item.ExtraData, cmbClientsforUser.SelectedValue, Environment.UserName)
                If ClassDatabase.Execute_non_Query(sql) = False Then
                    MsgBox(String.Format("Error in Adding User {0} to Client {1}", item.Text, cmbGroups_Group2User.Text), MsgBoxStyle.Critical)
                End If
            End If
        Next
        LoadUserForClient()
    End Sub
    Private Sub LoadUserForClient()
        Dim clientid
        Try
            clientid = cmbClientsforUser.SelectedValue
        Catch ex As Exception
            Exit Sub
        End Try
        If clientid Is Nothing Then Exit Sub
        If Not cmbClientsforUser.SelectedValue Is Nothing Then
            lblUser2Client.Text = "User for Client " & cmbClientsforUser.Text
            Dim SQL As String = String.Format("SELECT T1.GUID, T.USERNAME FROM TBDD_USER T, TBDD_CLIENT_USER T1 WHERE T1.USER_ID = T.GUID AND T1.CLIENT_ID = {0} ORDER BY T.USERNAME", cmbClientsforUser.SelectedValue)
            Try
                Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL)
                chklbxUsersforClient.Items.Clear()
                For Each row As DataRow In dt.Rows
                    chklbxUsersforClient.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
                Next
            Catch ex As Exception
                MsgBox("Error in LoadUserForClient:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If

    End Sub

    Private Sub cmbClientsforUser_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientsforUser.SelectedIndexChanged
        LoadUserForClient()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btndeleteUserfromClient.Click
        For Each obj As Object In chklbxUsersforClient.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql
            sql = String.Format("DELETE FROM TBDD_CLIENT_USER  WHERE GUID = {0}", item.ExtraData)
            If ClassDatabase.Execute_non_Query(sql, True) = False Then
                MsgBox(String.Format("Error in deleting User {0} from Client", item.Text), MsgBoxStyle.Critical)
            End If
        Next
        LoadUserForClient()
    End Sub
End Class