Imports System.Collections.Generic
Imports System.Data
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Interfaces
Imports DigitalData.Modules.Logging

Public Class ADSyncJob
    Inherits JobBase
    Implements IJob(Of ADSyncArgs)

    Public Sub New(LogConfig As LogConfig, MSSQL As MSSQLServer)
        MyBase.New(LogConfig, MSSQL)
    End Sub

    Public Sub Start(Arguments As ADSyncArgs) Implements IJob(Of ADSyncArgs).Start
        Dim oJobName As String = [GetType]().Name

        Try
            Dim oSync = New ActiveDirectoryInterface(_LogConfig, Arguments.RootPath)

            _Logger.Info("Running job {0}", oJobName)

            If oSync.Authenticate() = False Then
                _Logger.Warn("Job {0} could not be completed! Authentication failed!", oJobName)
                Exit Sub
            End If

            Dim oGroups = GetGroups()
            Dim oAttributeMappings = GetAttributeMappings()
            _Logger.Debug("Found {0} Groups", oGroups.Count)

            For Each oGroup In oGroups
                _Logger.Debug("Syncing Group [{0}]", oGroup)
                Dim oSyncedUsers = oSync.SyncUsersForGroup(oGroup, oAttributeMappings, _MSSQL, Arguments.UserFilter)

                If oSyncedUsers Is Nothing Then
                    _Logger.Warn("Group [{0}] could not be synced!", oGroup)
                ElseIf oSyncedUsers.Count > 0 Then
                    _Logger.Info("Processed [{0}] users for group [{1}]", oSyncedUsers.Count, oGroup)
                End If
            Next

            _Logger.Info("Job {0} completed!", oJobName)
        Catch ex As Exception
            _Logger.Warn("Job {0} failed!", oJobName)
            _Logger.Error(ex)
        End Try
    End Sub

    Private Function GetGroups() As List(Of String)
        Try
            Dim oGroups As New List(Of String)
            Dim oDatatable = _MSSQL.GetDatatable("SELECT NAME FROM TBDD_GROUPS WHERE AD_SYNC = 1 AND ACTIVE = 1")

            For Each oRow As DataRow In oDatatable.Rows
                oGroups.Add(oRow.Item("NAME"))
            Next

            Return oGroups
        Catch ex As Exception
            _Logger.Error(ex)
            Return New List(Of String)
        End Try
    End Function

    Private Function GetAttributeMappings() As List(Of AttributeMapping)
        Dim oDatatable = _MSSQL.GetDatatable("SELECT * FROM TBDD_EXTATTRIBUTES_MATCHING")

        Dim oAttributeMappings = New List(Of AttributeMapping)

        For Each oRow As DataRow In oDatatable.Rows
            oAttributeMappings.Add(New AttributeMapping() With {
                .AttributeName = oRow.Item("EXT_ATTRIBUTE"),
                .FirebirdSyskey = oRow.Item("FB_SYS_KEY"),
                .MSSQLColumn = oRow.Item("TBDD_USER_COLUMN")
            })
        Next

        Return oAttributeMappings
    End Function

    Public Function ShouldStart(Arguments As ADSyncArgs) As Boolean Implements IJob(Of ADSyncArgs).ShouldStart
        Return Arguments.Enabled
    End Function
End Class
