Imports DevExpress.XtraGrid.Views.Tile
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging

Public Class ChatAddUser
    Public Delegate Sub UserAdded()
    Public Event User_Added As UserAdded
    Private _Database As MSSQLServer
    Private LogConfig As LogConfig
    Private Logger As Logger

    Public ConversationID As Long
    Public ConnStringIDB As String
    Public Username As String
    Public User_Language As String
    Public NewConversation As Long

    Public Sub New()
        InitializeComponent()
    End Sub

    Public Sub Init(LogConfig As LogConfig, ConnectionStringIDB As String, CONV_ID As Long, Username As String, UserLanguage As String, DTUsers As DataTable)
        Me.LogConfig = LogConfig
        Me.Logger = LogConfig.GetLogger()
        Me.ConnStringIDB = ConnectionStringIDB
        ConversationID = CONV_ID

        Me.Username = Username
        Me.User_Language = UserLanguage
        Me._Database = New MSSQLServer(LogConfig, ConnectionStringIDB)
        If Not IsNothing(DTUsers) Then
            If DTUsers.Rows.Count > 1 Then
                GridControlUsers.DataSource = DTUsers
            End If

        End If
    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        AddUser()
    End Sub
    Public Function AddUser()
        Try
            Dim oSQL As String
            Dim oError As Boolean = False

            Dim oSelectedUsers As Integer() = GridViewUsers.GetSelectedRows()
            If oSelectedUsers.Count > 0 Then
                For Each oRowHandle As Integer In oSelectedUsers
                    Dim oUserID
                    Try
                        oUserID = GridViewUsers.GetRowCellValue(oRowHandle, "UserID")
                    Catch ex As Exception
                        Try
                            oUserID = GridViewUsers.GetRowCellValue(oRowHandle, "USER_ID")
                        Catch ex1 As Exception
                            Logger.Warn("Error Selecting UserID/USER_ID: " & ex.Message)
                            oError = True
                            Return False
                        End Try

                    End Try

                    oSQL = $"EXEC PRIDB_ADD_USER_2_CONVERSATION {ConversationID},{oUserID},'{Username}'"
                    If _Database.ExecuteNonQuery(oSQL) = False Then
                        oError = True
                    End If
                Next
            End If
            If oError = False Then
                RaiseEvent User_Added()
            End If


        Catch ex As Exception
            Logger.Error(ex)
            MsgBox($"Unexpected error in Add User2Conversation: {ex.Message}")
        End Try
    End Function
End Class
