Imports DigitalData.Modules.Interfaces
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Jobs

Public Class Form1
    Private _sync As ActiveDirectoryInterface
    Private _logConfig As LogConfig
    Private _logger As Logger
    Private _firebird As Firebird
    Private _sql As MSSQLServer
    Private _configManager As ConfigManager(Of ADConfig)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        _logConfig = New LogConfig(LogConfig.PathType.CurrentDirectory)
        _logConfig.Debug = True
        _logger = _logConfig.GetLogger()
        _firebird = New Firebird(_logConfig, "172.24.12.41", "172.24.12.41:E:\DB\Firebird\Databases\DD_ICM.fdb", "sysdba", "dd")
        _sql = New MSSQLServer(_logConfig, "Server=172.24.12.41\tests;Database=DD_ECM_TEST;User Id=sa; Password=dd")

        _sync = New ActiveDirectoryInterface(_logConfig)
        _sync.Authenticate()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim oGroup As String = ListBox1.SelectedItem
        Dim oAttributeMappings = GetAttributeMappings()
        _sync.SyncUsersForGroup(oGroup, oAttributeMappings, _firebird, _sql)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim oGroups = _sync.ListGroups()

        For Each oGroup In oGroups
            ListBox1.Items.Add(oGroup.Name)
        Next
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim oGroup As String = ListBox1.SelectedItem
        Dim oAttributeMappings = GetAttributeMappings()

        Dim oUsers = _sync.ListUsers(oGroup, oAttributeMappings)

        ListBox2.Items.Clear()
        For Each oUser In oUsers
            ListBox2.Items.Add(oUser.samAccountName)
        Next

        If oUsers.Count = 0 Then
            ListBox2.Items.Add("No users found ¯\_(ツ)_/¯")
        End If
    End Sub

    Private Function GetAttributeMappings() As List(Of AttributeMapping)
        Dim oDatatable = _sql.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

    Private Sub btnParseConfig_Click(sender As Object, e As EventArgs) Handles btnParseConfig.Click
        Dim oConfig = JobConfigParser.ParseConfig(txtJobConfigString.Text)
    End Sub
End Class
