Imports DevExpress.XtraSplashScreen
Imports DigitalData.Modules.Interfaces
Imports DigitalData.Modules.Logging
Imports DigitalData.GUIs.Common
Imports DevExpress.XtraGrid.Views.Grid

Public Class frmAdmin_UserImport
    Private ReadOnly Logger As Logger = My.LogConfig.GetLogger
    Private ActiveDirectory As ActiveDirectoryInterface

    Private Sub frmAdmin_ImportUser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ActiveDirectory = New ActiveDirectoryInterface(My.LogConfig, Nothing)

        Dim oGridManager = New GridBuilder(GridView1, GridView2)
        oGridManager.
            WithDefaults().
            WithReadOnlyOptions().
            WithClipboardHandler()
    End Sub

    Private Async Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        SplashScreenManager1.ShowWaitForm()
        SplashScreenManager1.SetWaitFormCaption("Loading Groups")

        Try
            Dim oGroups As List(Of ADGroup) = Await ActiveDirectory.ListGroupsAsync()
            Dim oGroupList As New List(Of GroupListing)

            For Each oGroup As ADGroup In oGroups
                Try
                    SplashScreenManager1.SetWaitFormDescription(oGroup.SAMAccountName)

                    Dim oUsers As List(Of ADUser) = Await ActiveDirectory.ListUsersAsync(oGroup.Name)
                    Dim oListing As New GroupListing(oGroup) With {
                        .Count = oUsers.Count,
                        .Users = oUsers
                    }

                    If oUsers.Count > 0 Then
                        oGroupList.Add(oListing)
                    End If

                Catch ex As Exception
                    Logger.Error(ex)
                End Try
            Next

            gridGroupList.ForceInitialize()
            gridGroupList.DataSource = oGroupList

        Catch ex As Exception
            Logger.Error(ex)
        Finally
            SplashScreenManager1.CloseWaitForm()
        End Try
    End Sub

    Private Sub btnImportUsers_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnImportUsers.ItemClick
        Dim oForm As New frmAdmin_UserImport()
        oForm.ShowDialog()
    End Sub

    Private Sub GridView1_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim oGroup As GroupListing = GridView1.GetRow(e.FocusedRowHandle)

        If Not IsNothing(oGroup) Then
            Try
                gridUserList.DataSource = oGroup.Users

            Catch ex As Exception
                Logger.Error(ex)
            End Try
        End If
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Dim oSelected = GridView2.GetSelectedRows()
        Dim oDialogResult = MsgBox($"Wollen Sie die ausgewählten [{oSelected.Count}] Benutzer importieren?",
                                   MsgBoxStyle.Question Or MsgBoxStyle.YesNo,
                                   "Import von Benutzern")

        If DialogResult.No = oDialogResult Then
            Exit Sub
        End If

        Dim oImported = 0
        Dim oSkipped = 0

        Try
            For Each oHandle In oSelected
                Dim oRow As ADUser = GridView2.GetRow(oHandle)

                If Not UserExists(oRow.samAccountName) Then
                    If InsertUser(oRow.samAccountName, oRow.Surname, oRow.GivenName, oRow.Email) Then
                        oImported += 1
                    Else
                        Logger.Warn("User [{0}] could not be imported!", oRow.samAccountName)
                    End If
                Else
                    If UpdatetUser(oRow.samAccountName, oRow.Surname, oRow.GivenName, oRow.Email) Then
                        oImported += 1
                    Else
                        Logger.Warn("User [{0}] could not be updated!", oRow.samAccountName)
                        oSkipped += 1
                    End If

                End If
            Next

            If oImported = 0 Then
                Logger.Warn("No new users imported. All selected users are already in database.")
                MsgBox($"Es wurden keine neuen Benutzer importiert, da alle ausgewählten Benutzer bereits in der Benutzerverwaltung vorhanden sind.", MsgBoxStyle.Exclamation, "UserManager")
            Else
                Logger.Info($"Import successful!{vbNewLine}{vbNewLine}{oImported} users imported{vbNewLine}{oSkipped} users skipped")
                MsgBox($"{oImported} Benutzer wurden erfolgreich importiert!", MsgBoxStyle.Information, Text)
            End If
        Catch ex As Exception
            Logger.Error(ex, "Error while importing users")
            MsgBox($"Error while importing users: {ex.Message}", MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Dim oSelected = GridView1.GetSelectedRows()
        Dim oMessage = $"Wollen Sie die ausgewählten [{oSelected.Count}] Gruppen importieren? Achtung: Es werden NUR die GRUPPEN importiert, nicht die enthaltenen Benutzer!"
        Dim oDialogResult = MsgBox(oMessage,
                                   MsgBoxStyle.Question Or MsgBoxStyle.YesNo,
                                   "Import von Gruppen")

        If DialogResult.No = oDialogResult Then
            Exit Sub
        End If

        Dim oImported = 0
        Dim oSkipped = 0

        Try
            For Each oHandle In oSelected
                Dim oRow As ADGroup = GridView2.GetRow(oHandle)

                If Not GroupExists(oRow.SAMAccountName) Then
                    If InsertGroup(oRow.SAMAccountName) Then
                        oImported += 1
                    Else
                        Logger.Warn("Group [{0}] could not be imported!", oRow.SAMAccountName)
                    End If
                Else
                    oSkipped += 1
                End If
            Next

            If oImported = 0 Then
                Logger.Warn("No new groups imported. All selected groups are already in database.")
                MsgBox($"Es wurden keine neuen Gruppen importiert, da alle ausgewählten Gruppen bereits in der Gruppenverwaltung vorhanden sind.", MsgBoxStyle.Exclamation, "UserManager")
            Else
                Logger.Info($"Import successful!{vbNewLine}{vbNewLine}{oImported} groups imported{vbNewLine}{oSkipped} groups skipped")
                MsgBox($"{oImported} Gruppen wurden erfolgreich importiert!", MsgBoxStyle.Information, Text)
            End If
        Catch ex As Exception
            Logger.Error(ex, "Error while importing users")
            MsgBox($"Error while importing users: {ex.Message}", MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Function GroupExists(groupName As String) As Boolean
        Try
            Dim oSql As String = $"SELECT COUNT(GUID) FROM TBDD_GROUPS WHERE NAME = '{groupName}'"
            Dim oResult = My.DatabaseECM.GetScalarValue(oSql)

            Return Convert.ToBoolean(oResult)
        Catch ex As Exception
            Logger.Error($"Error in GroupExists: {ex.Message}")
            Return Nothing
        End Try
    End Function

    Public Function UserExists(userName As String) As Boolean
        Try
            Dim oSql As String = $"SELECT COUNT(GUID) FROM TBDD_USER WHERE USERNAME = '{userName}'"
            Dim oResult = My.DatabaseECM.GetScalarValue(oSql)

            Return Convert.ToBoolean(oResult)
        Catch ex As Exception
            Logger.Error($"Error in UserExists: {ex.Message}")
            Return Nothing
        End Try
    End Function

    Public Function InsertUser(username As String, prename As String, name As String, email As String)
        Try
            Dim oAddedWho As String = Environment.UserName
            Dim oSql As String = $"INSERT INTO TBDD_USER (PRENAME, NAME, USERNAME, EMAIL, ADDED_WHO) 
                                  VALUES ('{prename}','{name}','{username}','{email}','{oAddedWho}')"
            Dim oResult = My.DatabaseECM.ExecuteNonQuery(oSql)

            Return oResult
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Public Function UpdatetUser(username As String, prename As String, name As String, email As String)
        Try
            Dim oAddedWho As String = Environment.UserName
            Dim oSql As String = $"UPDATE TBDD_USER SET PRENAME = '{prename}', NAME = '{name}', EMAIL = , CHANGED_WHO = '{Environment.UserName}' WHERE USERNAME = '{username}')"
            Dim oResult = My.DatabaseECM.ExecuteNonQuery(oSql)

            Return oResult
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Public Function InsertGroup(name As String, Optional ECM_FK_ID As Integer = 1, Optional adSync As Boolean = True, Optional internal As Boolean = False, Optional active As Boolean = True)
        Try
            Dim addedWho As String = Environment.UserName
            Dim sql As String = $"INSERT INTO TBDD_GROUPS (NAME, ADDED_WHO, ECM_FK_ID, AD_SYNC, INTERNAL, ACTIVE) 
                                  VALUES ('{name}', '{addedWho}', {ECM_FK_ID}, 
                                  {Convert.ToInt32(adSync)}, 
                                  {Convert.ToInt32(internal)}, 
                                  {Convert.ToInt32(active)})"
            Dim oResult = My.DatabaseECM.ExecuteNonQuery(sql)

            Return True
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function

    Private Class GroupListing
        Public Group As ADGroup
        Public Users As List(Of ADUser)
        Public Property Count As Integer
        Public ReadOnly Property Name As String
            Get
                Return Group?.Name
            End Get
        End Property

        Public Sub New(pGroup As ADGroup)
            Group = pGroup
            Count = 0
        End Sub
    End Class


End Class