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.VWPMO_USERS_GROUPS". Sie können sie bei Bedarf verschieben oder entfernen.
        'Me.VWPMO_USERS_GROUPSTableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_USERS_GROUPS)
        Load_User()
    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)
        Catch ex As Exception
            MsgBox("Error in frmUserKonfig_Load:" & 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 user As DataRowView = GetSelectedUserObject()
        Try
            Dim userID As Integer = user.Item(0)
        Catch ex As Exception
            Exit Sub
        End Try
        If Not user Is Nothing Then
            Dim userID As Integer = user.Item(0)
            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 If
       
    End Sub

    Private Sub TBDD_USERBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBDD_USERBindingSource.PositionChanged
        LoadGroupsForSelectedUser()
    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
        Load_Groups()
    End Sub
End Class