Imports DigitalData.GUIs.Common
Imports DigitalData.GUIs.Common.Base

Public Class frmAdmin_UserGroupRelations
    Implements IBaseForm, IAdminForm

    Public ReadOnly Property LogConfig As Modules.Logging.LogConfig Implements IBaseForm.LogConfig
    Public ReadOnly Property Logger As Modules.Logging.Logger Implements IBaseForm.Logger


    Public Property PrimaryKey As Integer Implements IAdminForm.PrimaryKey
    Public Property HasChanges As Boolean Implements IAdminForm.HasChanges
    Public Property IsInsert As Boolean Implements IAdminForm.IsInsert

    Private Property SelectedGroupId As Integer = Nothing
    Private Property SelectedAvailableUser As Integer = Nothing
    Private Property SelectedRelatedUser As Integer = Nothing
    Private FormHelper As FormHelper = Nothing

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

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        LogConfig = My.LogConfig
        FormHelper = New FormHelper(LogConfig, Me)
    End Sub

    Private Async Sub frmAdmin_UserGroupRelations_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim DragDropManager = New ClassDragDrop(LogConfig)
            DragDropManager.AddGridView(GridView1)
            DragDropManager.AddGridView(GridView3)

            Dim GridBuilder = New GridBuilder(GridView1, GridView2, GridView3)
            GridBuilder.
                WithDefaults().
                WithReadOnlyOptions()

            Dim oSQL = "SELECT * FROM TBDD_GROUPS"
            Dim oTable As DataTable = Await My.DatabaseECM.GetDatatableAsync(oSQL)
            GridControl2.DataSource = oTable
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "Fehler beim Laden des Formulars")
        End Try
    End Sub

    Private Async Function GetAvailableUsersByGroupId(pGroupId As Integer) As Threading.Tasks.Task(Of DataTable)
        Try
            Dim oSql As String = $"
                SELECT  GUID, PRENAME, NAME, USERNAME, SHORTNAME, EMAIL, LANGUAGE, COMMENT, DATE_FORMAT, ADDED_WHO, ADDED_WHEN, CHANGED_WHO, CHANGED_WHEN
                FROM    TBDD_USER
                WHERE   (GUID NOT IN
                        (SELECT DISTINCT T.GUID
                        FROM            TBDD_USER AS T INNER JOIN TBDD_GROUPS_USER AS T1 ON T.GUID = T1.USER_ID
                        WHERE        (T1.GROUP_ID = {pGroupId})))
            "
            Dim oTable = Await My.DatabaseECM.GetDatatableAsync(oSql)
            Return oTable
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "GetAvailableUsersByGroupId")
            Return Nothing
        End Try
    End Function

    Private Async Function GetRelatedUsersByGroupId(pGroupId As Integer) As Threading.Tasks.Task(Of DataTable)
        Try
            Dim oSql As String = $"            
                SELECT  T1.GUID, T1.PRENAME, T1.NAME, T1.USERNAME, T1.SHORTNAME, T1.EMAIL, T1.LANGUAGE, T1.COMMENT, T1.DATE_FORMAT, T1.ADDED_WHO, T1.ADDED_WHEN, T1.CHANGED_WHO, T1.CHANGED_WHEN
                FROM    TBDD_USER AS T1 INNER JOIN
                        TBDD_GROUPS_USER AS T2 ON T1.GUID = T2.USER_ID
                WHERE   (T2.GROUP_ID = {pGroupId})
            "
            Dim oTable = Await My.DatabaseECM.GetDatatableAsync(oSql)
            Return oTable
        Catch ex As Exception
            FormHelper.ShowErrorMessage(ex, "GetRelatedUsersByGroupId")
            Return Nothing
        End Try
    End Function

    Public Function DeleteData() As Boolean Implements IAdminForm.DeleteData
        Throw New NotImplementedException()
    End Function

    Private Async Sub GridView2_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView2.FocusedRowChanged
        Dim oRowView As DataRowView = GridView2.GetRow(GridView2.FocusedRowHandle)
        Dim oRow As DataRow = oRowView.Row

        If oRow IsNot Nothing Then
            SelectedGroupId = oRow.Item("GUID")
            Await UpdateUsers(SelectedGroupId)

        End If
    End Sub

    Private Sub GridView1_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Try
            SelectedAvailableUser = GridView1.GetFocusedRowCellValue("GUID")
        Catch ex As Exception
            SelectedAvailableUser = 0
        End Try
    End Sub

    Private Sub GridView3_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView3.FocusedRowChanged
        Try
            SelectedRelatedUser = GridView3.GetFocusedRowCellValue("GUID")
        Catch ex As Exception
            SelectedRelatedUser = 0
        End Try
    End Sub

    Private Async Function UpdateUsers(pGroupId As Integer) As Threading.Tasks.Task
        Dim oAvailableTable = Await GetAvailableUsersByGroupId(SelectedGroupId)
        GridControl1.DataSource = oAvailableTable

        Dim oRelatedTable = Await GetRelatedUsersByGroupId(SelectedGroupId)
        GridControl3.DataSource = oRelatedTable
    End Function

    Private Async Sub GridControl1_DragDrop(sender As Object, e As DragEventArgs) Handles GridControl1.DragDrop
        Dim oData As String = e.Data.GetData(DataFormats.Text)
        Dim oGuid As Integer = oData.Split("|").ToList.First()

        If Await RemoveUserFromGroup(oGuid, SelectedGroupId) Then
            Await UpdateUsers(SelectedGroupId)
        End If
    End Sub

    Private Async Sub GridControl3_DragDrop(sender As Object, e As DragEventArgs) Handles GridControl3.DragDrop
        Dim oData As String = e.Data.GetData(DataFormats.Text)
        Dim oGuid As Integer = oData.Split("|").ToList.First()

        If Await AddUserToGroup(oGuid, SelectedGroupId) Then
            Await UpdateUsers(SelectedGroupId)
        End If
    End Sub

    Private Async Function AddUserToGroup(pUserId As Integer, pGroupId As Integer) As Threading.Tasks.Task(Of Boolean)
        Try
            Dim oUser = My.Application.User.UserName
            Dim oSql = $"
                INSERT INTO TBDD_GROUPS_USER 
                (USER_ID, GROUP_ID, COMMENT, ADDED_WHO)
                VALUES (
                    {pUserId},
                    {pGroupId},
                    'Assign User {pUserId} to Group {pGroupId}',
                    '{oUser}'
                )"
            Return Await My.DatabaseECM.ExecuteNonQueryAsync(oSql)

        Catch ex As Exception
            Logger.error(ex)
            Return False

        End Try
    End Function

    Private Async Function RemoveUserFromGroup(pUserId As Integer, pGroupId As Integer) As Threading.Tasks.Task(Of Boolean)
        Try
            Dim oUser = My.Application.User.UserName
            Dim oSql = $"
                DELETE FROM TBDD_GROUPS_USER
                WHERE USER_ID = {pUserId} AND GROUP_ID = {pGroupId}
            "
            Return Await My.DatabaseECM.ExecuteNonQueryAsync(oSql)

        Catch ex As Exception
            Logger.Error(ex)
            Return False

        End Try
    End Function

    Private Async Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles SimpleButton2.Click
        If SelectedAvailableUser > 0 Then
            Await AddUserToGroup(SelectedAvailableUser, SelectedGroupId)
            Await UpdateUsers(SelectedGroupId)
        End If
    End Sub

    Private Async Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        If SelectedRelatedUser > 0 Then
            Await RemoveUserFromGroup(SelectedRelatedUser, SelectedGroupId)
            Await UpdateUsers(SelectedGroupId)
        End If
    End Sub
End Class