Imports DigitalData.Modules.Logging

Public Class frmUserManager
    Private _Logger As Logger

    Private _UserTable As DataTable
    Private _GroupTable As DataTable
    Private _UserToGroupTable As DataTable
    Private _GroupToGroupTable As DataTable

    Private _UserToGroupControl As UserControlAssignment
    Private _GroupToGroupControl As UserControlAssignment

    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        _Logger = My.LogConfig.GetLogger()
    End Sub

    Private Async Sub frmUserManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Await InitDataAsync()

        UserNavbar.SelectedItem = NavbarUser2Group
    End Sub

    Private Sub ShowUserToGroupControl()
        If _UserToGroupControl Is Nothing Then
            _UserToGroupControl = New UserControlAssignment() With {
                .TextAssignedToParent = "Zugeordnete Benutzer",
                .TextNotAssignedToParent = "Nicht zugeordnete Benutzer",
                .TextParentList = "Verfügbare Gruppen",
                .Dock = DockStyle.Fill
            }

            AddHandler _UserToGroupControl.ChildAdded, AddressOf HandleUserAddedToGroup
            AddHandler _UserToGroupControl.ChildRemoved, AddressOf HandleUserRemovedFromGroup

            _UserToGroupControl.Init(_GroupTable, _UserTable, _UserToGroupTable, "GROUP_ID", "USER_ID")

            ContentPanel.Controls.Add(_UserToGroupControl)
        End If

        _UserToGroupControl.Visible = True
    End Sub

    Private Sub ShowGroupToGroupControl()
        If _GroupToGroupControl Is Nothing Then
            _GroupToGroupControl = New UserControlAssignment() With {
                .TextAssignedToParent = "Zugeordnete Gruppen",
                .TextNotAssignedToParent = "Nicht zugeordnete Gruppen",
                .TextParentList = "Verfügbare Gruppen",
                .Dock = DockStyle.Fill
            }

            AddHandler _GroupToGroupControl.ChildAdded, AddressOf HandleGroupAddedToGroup
            AddHandler _GroupToGroupControl.ChildRemoved, AddressOf HandleGroupRemovedFromGroup

            _GroupToGroupControl.Init(_GroupTable, _GroupTable, _GroupToGroupTable, "GROUP2_ID", "GROUP1_ID")

            _ContentPanel.Controls.Add(_GroupToGroupControl)
        End If

        _GroupToGroupControl.Visible = True
    End Sub

    Private Async Function InitDataAsync() As Task
        _UserTable = Await GetAttributeListAsync("User")
        _GroupTable = Await GetAttributeListAsync("Group")
        _UserToGroupTable = Await GetAttributeListAsync("User2Group")
        _GroupToGroupTable = Await GetAttributeListAsync("Group2Group")
    End Function

    Private Async Function UpdateDataAsync() As Task
        _UserTable = Await GetAttributeListAsync("User")
        _GroupTable = Await GetAttributeListAsync("Group")
        _UserToGroupTable = Await GetAttributeListAsync("User2Group")
        _GroupToGroupTable = Await GetAttributeListAsync("Group2Group")

        _UserToGroupControl.UpdateData(_GroupTable, _UserTable, _UserToGroupTable)
        _GroupToGroupControl.UpdateData(_GroupTable, _GroupTable, _GroupToGroupTable)
    End Function

    Private Async Sub HandleUserAddedToGroup(GroupId As Integer, UserId As Integer, RelationRecordId As Integer)
        Dim oRecordId = Await My.Common.Commands.FNIDB_RADM_NEW_USER2GROUP(UserId, GroupId)

        Await UpdateDataAsync()
    End Sub

    Private Async Sub HandleUserRemovedFromGroup(GroupId As Integer, UserId As Integer, RelationRecordId As Integer)
        Dim oResult = Await My.Common.Commands.FNIDB_DELETE_RECORD_FINALLY(RelationRecordId)

        Await UpdateDataAsync()
    End Sub

    Private Async Sub HandleGroupAddedToGroup(ParentGroupId As Integer, GroupId As Integer, RelationRecordId As Integer)
        Dim oRecordId = Await My.Common.Commands.FNIDB_RADM_NEW_GROUP2GROUP(GroupId, ParentGroupId)

        Await UpdateDataAsync()
    End Sub

    Private Async Sub HandleGroupRemovedFromGroup(ParentGroupId As Integer, GroupId As Integer, RelationRecordId As Integer)
        Dim oResult = Await My.Common.Commands.FNIDB_DELETE_RECORD_FINALLY(RelationRecordId)

        Await UpdateDataAsync()
    End Sub

    Private Async Function GetAttributeListAsync(AttributeName As String) As Task(Of DataTable)
        Try
            Dim oSQL = $"SELECT * FROM VWIDB_{AttributeName.ToUpper}"
            Dim oRequest = Await My.Channel.CreateDatabaseRequestAsync($"List Attribute {AttributeName}", False)
            Dim oResult = Await My.Channel.ReturnDatatableAsync(oSQL)

            Await My.Channel.CloseDatabaseRequestAsync()

            Return oResult.Table
        Catch ex As Exception
            _Logger.Error(ex)
            Throw ex
        End Try
    End Function

    Private Sub BarButtonUserEdit_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonUserEdit.ItemClick
        Dim oForm As New frmObjectEditor(ClassConstants.DB_USER_ATTRIBUTE_ID, ClassConstants.DB_USER_ATTRIBUTE_SYSKEY, _UserTable)
        oForm.Show()
    End Sub

    Private Sub BarButtonGroupEdit_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonGroupEdit.ItemClick
        Dim oForm As New frmObjectEditor(ClassConstants.DB_GROUP_ATTRIBUTE_ID, ClassConstants.DB_GROUP_ATTRIBUTE_SYSKEY, _GroupTable)
        oForm.Show()
    End Sub

    Private Async Sub BarButtonRefresh_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonRefresh.ItemClick
        Await UpdateDataAsync()
    End Sub

    Private Sub OfficeNavigationBar1_SelectedItemChanged(sender As Object, e As DevExpress.XtraBars.Navigation.NavigationBarItemEventArgs) Handles UserNavbar.SelectedItemChanged
        ' Hide all UserControls
        For Each oControl As Control In ContentPanel.Controls
            oControl.Visible = False
        Next

        ' Then check the currently selected navbar item and show the corresponding UserControl
        If UserNavbar.SelectedItem.Equals(NavbarUser2Group) Then
            ShowUserToGroupControl()
        ElseIf UserNavbar.SelectedItem.Equals(NavbarGroup2Group) Then
            ShowGroupToGroupControl()
        End If
    End Sub


End Class