Imports System.DirectoryServices
Imports System.DirectoryServices.ActiveDirectory
Imports System.DirectoryServices.AccountManagement

Public Class frmUserKonfig_AddUsers

    Private Sub formUserConfig_AddUsers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Cursor = Cursors.WaitCursor
            Dim groups As List(Of String) = GetActiveDirectoryGroups()

            For Each group In groups
                lbGroups.Items.Add(group)
            Next
        Catch ex As Exception
            MsgBox("Error in Load Groups:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Cursor = Cursors.Default
       
    End Sub

    Function GetActiveDirectoryGroups() As List(Of String)
        Dim groups As List(Of String) = New List(Of String)
        Dim ctx As PrincipalContext = New PrincipalContext(ContextType.Domain)
        Dim group As GroupPrincipal = New GroupPrincipal(ctx)
        Dim srch As PrincipalSearcher = New PrincipalSearcher(group)
        For Each g In srch.FindAll()
            If GetUsersForGroup(g.ToString()).Count <> 0 Then
                groups.Add(g.ToString)
            End If
        Next

        Return groups
    End Function


    Function GetUsersForGroup(g As String) As List(Of UserPrincipal)
        Dim users As List(Of UserPrincipal) = New List(Of UserPrincipal)
        Dim ctx As PrincipalContext = New PrincipalContext(ContextType.Domain)
        Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, g)

        Dim u = group.GetMembers(True)

        For Each user In u
            If user.GetType().Name = "UserPrincipal" Then
                users.Add(user)
            End If
        Next

        Return users
    End Function

    Private Sub lbGroups_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lbGroups.SelectedIndexChanged
        Dim group As String = lbGroups.SelectedItem
        Dim users As List(Of UserPrincipal) = GetUsersForGroup(group)

        clbUsers.Items.Clear()
        For Each user In users
            clbUsers.Items.Add(user)
        Next
    End Sub

    Private Sub btnAddUsers_Click(sender As Object, e As EventArgs) Handles btnAddUsers.Click
        Dim items As CheckedListBox.CheckedItemCollection = clbUsers.CheckedItems
        Dim usersAdded As Integer = 0

        If items.Count = 0 Then
            MsgBox("Keine Benutzer ausgewählt!", MsgBoxStyle.Information)
            Exit Sub
        End If

        For Each item As UserPrincipal In items
            Dim user As UserPrincipal = item
            Dim PRENAME As String = user.GivenName
            Dim NAME As String = user.Surname
            Dim USERNAME As String = user.SamAccountName
            Dim email As String = user.EmailAddress
            Dim SQL
            If Not UserExists(USERNAME) Then
                SQL = "INSERT INTO TBDD_USER(PRENAME, NAME, USERNAME, EMAIL, MODULE_RECORD_ORG) VALUES('" & PRENAME & "', '" & NAME & "', '" & USERNAME & "','" & email & "'," & 1 & ")"
                If ClassDatabase.Execute_non_Query(SQL) = True Then
                    usersAdded = usersAdded + 1
                End If
            Else
                SQL = "UPDATE TBDD_USER SET MODULE_RECORD_ORG = 1 WHERE UPPER(USERNAME) = UPPER('" & USERNAME & "')"
                If ClassDatabase.Execute_non_Query(SQL) = True Then
                    usersAdded = usersAdded + 1
                End If
            End If
        Next

        If usersAdded = 1 Then
            MsgBox(usersAdded & " neuer Benutzer hinzugefügt", MsgBoxStyle.Information)
        Else
            MsgBox(usersAdded & " neue Benutzer hinzugefügt", MsgBoxStyle.Information)
        End If

    End Sub

    Private Function UserExists(username As String) As Boolean
        Try
            Dim SQL = "SELECT GUID FROM TBDD_USER WHERE UPPER(USERNAME) = UPPER('" & username & "')"
            If ClassDatabase.Execute_Scalar(SQL) = Nothing Then
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            MsgBox("Error in UserExists: " & vbNewLine & ex.Message)
            Return False
        End Try
    End Function

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub tbSelectEverything_Click(sender As Object, e As EventArgs) Handles tbSelectEverything.Click
        For i = 0 To clbUsers.Items.Count - 1
            clbUsers.SetItemChecked(i, True)
        Next
    End Sub

    Private Sub tbSelectNone_Click(sender As Object, e As EventArgs) Handles tbSelectNone.Click
        For i = 0 To clbUsers.Items.Count - 1
            clbUsers.SetItemChecked(i, False)
        Next
    End Sub

    Private Sub clbUsers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles clbUsers.SelectedIndexChanged
        ToolTipController1.HideHint()
        Dim userstring As String = clbUsers.SelectedItem.ToString
        Dim userldap As UserPrincipal = clbUsers.SelectedItem
        Dim PRENAME As String = userldap.GivenName
        Dim NAME As String = userldap.Surname
        Dim USERNAME As String = userldap.SamAccountName
        Dim email As String = userldap.EmailAddress
        ToolTipController1.ShowHint("Used ldap paramters:", userstring & USERNAME & vbNewLine & email, DevExpress.Utils.ToolTipLocation.RightCenter)
    End Sub
End Class