Imports System.Drawing
Imports System.Windows.Forms
Imports com.sun.xml.internal.ws.resources

Public Class usrCntlMessenger_ListNewChats

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    Sub intiDGVChats(Optional dgv_ChatID = -1, Optional reloadChat = True, Optional selFirst = False)



        With dgvChats
            'Dim loadedTmp = loaded
            'If Not reloadChat Then
            '    loaded = False
            'End If

            Dim whereName = ""
            'If MyTextBox1.Text.Trim <> String.Empty Then
            '    whereName = " WHERE y.chat_name LIKE '%" & MyTextBox1.Text.Trim & "%' "
            'End If

            Dim where = ""
            'Select Case toggle_CHAT_ART
            '    Case "CHAT"
            '        where = " AND chat_art IN ('CHAT') "
            '        'Case "LKW_CHAT"
            '        '    where = " AND chat_art IN ('LKW_CHAT') "
            '    Case Else
            '        where = " AND chat_art IN ('" & toggle_CHAT_ART & "') "
            'End Select

            Dim sqlQery_optimiced As String = " SELECT * FROM (SELECT TOP 200
                                                c.chat_id,
                                                c.chat_art,
                                                CASE 
                                                    WHEN ISNULL(c.chat_name, '') <> '' THEN c.chat_name
                                                    ELSE names.chat_name
                                                END AS chat_name,
                                            
                                                ISNULL(unread.ungelesen, 0) AS ungelesen,
                                            
                                                c.chat_lastMsg
                                            
                                            FROM tblMessenger_Chat c
                                            
                                            -- ensure current user is member
                                            INNER JOIN tblMessenger_ChatMembers m
                                                ON m.chatMb_chatId = c.chat_id
                                                AND m.chatMb_maId = " & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "
                                            
                                            -- 🔹 get participant names (distinct!)
                                            OUTER APPLY (
                                                SELECT STRING_AGG(name, ', ') AS chat_name
                                                FROM (
                                                    SELECT DISTINCT 
                                                        mit.mit_vname + ' ' + mit.mit_nname AS name
                                                    FROM tblMessenger_ChatMembers m2
                                                    INNER JOIN tblMitarbeiter mit
                                                        ON mit.mit_id = m2.chatMb_maId
                                                    WHERE m2.chatMb_chatId = c.chat_id
                                                    AND m2.chatMb_maId <> " & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "
                                                ) x
                                            ) names
                                            
                                            -- 🔹 unread count separated (no duplication!)
                                            OUTER APPLY (
                                                SELECT COUNT(*) AS ungelesen
                                                FROM tblMessenger_ChatMessages msg
                                                INNER JOIN tblMessenger_ChatMessageStatus s
                                                    ON s.chatMgSt_chatMsgId = msg.chatMg_id
                                                WHERE msg.chatMg_chatId = c.chat_id
                                                  AND s.chatMgSt_MaId = " & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "
                                                  AND s.chatMgSt_gelesen = 0
                                              ) unread   WHERE c.chat_aktiv = 1
                                                    AND ISNULL(unread.ungelesen, 0) > 0
                                                    " & where & " ORDER BY c.chat_lastMsg DESC) y " & whereName



            .DataSource = SQL.loadDgvBySql(sqlQery_optimiced, "ADMIN")

            If .Columns.Count = 0 Then Exit Sub

            .Columns("chat_id").Visible = False
            .Columns("chat_lastMsg").Visible = False
            .Columns("chat_name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("chat_art").HeaderText = "ART"
            .Columns("ungelesen").Width = 30
            .Columns("ungelesen").HeaderText = "neu"
            .Columns("ungelesen").DefaultCellStyle.ForeColor = Color.White
            .Columns("ungelesen").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("ungelesen").DefaultCellStyle.Font = New Font(.Font.FontFamily, 7, FontStyle.Bold)

            dgvChats.GetOrder()

            If selFirst Then

                'dgvChats.ClearSelection()
                'SplitContainer1.Enabled = False

                'If .Rows.Count > 0 Then
                '    loaded = True
                '    SplitContainer1.Enabled = True
                '    .Rows(0).Selected = True
                'End If
                'loaded = loadedTmp
            Else



                dgvChats.ClearSelection()
                'If dgv_ChatID > 0 Then
                '    For Each r As DataGridViewRow In .Rows
                '        If r.Cells("chat_id").Value = dgv_ChatID Then
                '            dgvChats.ClearSelection()
                '            r.Selected = True : Exit For
                '        End If
                '    Next
                'End If
                'loaded = loadedTmp

            End If
            dgvChats.SetOrder()
            If dgvChats.SelectedRows.Count > 0 Then dgvChats.FirstDisplayedCell = dgvChats.SelectedRows(0).Cells("chat_name")
            'dgvChats.ClearSelection()
            'SplitContainer1.Enabled = False

            'If dgv_ChatID > 0 Then
            '    For Each r As DataGridViewRow In .Rows
            '        If r.Cells("chat_id").Value = dgv_ChatID Then
            '            dgvChats.ClearSelection()
            '            SplitContainer1.Enabled = True
            '            r.Selected = True : Exit For
            '        End If
            '    Next
            'End If


        End With
        ' If Not selFirst Then rtbChatMessage.Focus()

    End Sub

    Private Sub usrCntlMessenger_ListNewChats_Load(sender As Object, e As EventArgs) Handles Me.Load
        intiDGVChats()
        TimerNEW_MESSAGE.Enabled = True
    End Sub

    Private Sub TimerNEW_MESSAGE_Tick(sender As Object, e As EventArgs) Handles TimerNEW_MESSAGE.Tick
        intiDGVChats()
    End Sub
    Private Sub MyDatagridview1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvChats.CellDoubleClick '.CellContentClick
        For Each openForm In Application.OpenForms()
            If TypeOf (openForm) Is VERAG_PROG_ALLGEMEIN.frmMessenger Then
                CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).WindowState = FormWindowState.Normal
                CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).BringToFront()
                Exit Sub
            End If
        Next

        Dim f As New VERAG_PROG_ALLGEMEIN.frmMessenger()
        f.Location = Cursor.Position
        f.Show()
    End Sub
End Class
