Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms

Public Class frmMessenger
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Dim CHAT As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat = Nothing
    Dim MSG_LISTENDER As New cMessangerListender
    Dim topMessages As String = "20"
    Dim topMessagesDateHistory As Object = Nothing
    Dim loaded = False
    Public EMOJI_PATH_MAIN = DATENVERVER_OPTIONS.getRootDir & "\DOKUMENTE\CHAT_EMOJIS\"
    Public EMOJI_PATH = ""

    Dim alloweasteregg = False

    Public Sub New()

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

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Sub initEMOJI_PATH()

        EMOJI_PATH = EMOJI_PATH_MAIN
        Try
            Dim IPADDR As System.Net.IPAddress
            IPADDR = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList(0)

            If IPADDR.ToString.Contains("172.16.1.") Then 'WAIDHAUS
                EMOJI_PATH = "\\172.16.1.100\f\PROGRAMME\CHAT_EMOJIS\"
            End If

            If IPADDR.ToString.Contains("192.168.133.") Then 'SALZBURG
                EMOJI_PATH = "\\192.168.133.98\f\Programme\CHAT_EMOJIS\"
            End If

            If IPADDR.ToString.Contains("192.168.32.") Then 'NICKELSDORF
                EMOJI_PATH = "\\192.168.32.253\Files\Programme\CHAT_EMOJIS\"
            End If

            If IPADDR.ToString.Contains("192.168.100") Then 'NEUHAUS
                EMOJI_PATH = "\\192.168.100.20\Share\Programme\CHAT_EMOJIS\"
            End If

            If Not IO.Directory.Exists(EMOJI_PATH) Then
                EMOJI_PATH = EMOJI_PATH_MAIN
            End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub
    Private Sub MyDatagridview1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvChats.CellContentClick, dgvChats.CellClick
        If dgvChats.Rows(e.RowIndex).Cells("ungelesen").Value <> "" Then
            Dim dgv_ChatID = If(dgvChats.SelectedRows.Count > 0, dgvChats.SelectedRows(0).Cells("chat_id").Value, -1)
            intiDGVChats(dgv_ChatID, False) ' Splate ungelesen sol sich ändern
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim f As New frmMessenger_NeuerChat
        f.ShowDialog(Me)

        If f.chat_id > 0 Then
            'Dim dgv_ChatID = If(dgvChats.SelectedRows.Count > 0, dgvChats.SelectedRows(0).Cells("chat_id").Value, -1)
            intiDGVChats(f.chat_id)
        End If
    End Sub

    Private Sub frmMessenger_Load(sender As Object, e As EventArgs) Handles Me.Load
        initEMOJI_PATH()

        rtbChatMessage.AllowDrop = True
        MSG_LISTENDER.START()
        TimerNEW_MESSAGE.Enabled = True
        intiDGVChats()

        If My.Application.Info.AssemblyName = "SDL" Then
            lbl.Text = "CHAT"
        End If
        MyFlowLayoutPanel1.Controls.Clear()
        'loaded = True
        alloweasteregg = cAllgemein.MITARBEITER.mit_ChatEasteregg
        initEmojis()
    End Sub

    Sub initEmojis()
        FlowLayoutPanel.Controls.Clear()
        If alloweasteregg Then pic.Visible = False



        ' If IO.Directory.Exists(My.Application.roo "") Then

        Dim spezialEmoji = False
        If VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME = "ADMIN" Then spezialEmoji = True

        If IO.Directory.Exists(EMOJI_PATH) Then
            For Each aa In IO.Directory.GetFiles(EMOJI_PATH) '.OrderBy(Function(f) f)
                If alloweasteregg Or Not aa.Contains("easteregg") Then
                    If IO.File.Exists(aa) And aa.Contains(".png") And (aa.Contains("emoji_") Or spezialEmoji) Then

                        Dim p As New PictureBox
                        p.Size = New Size(40, 40)
                        p.BackgroundImage = Image.FromFile(aa)
                        p.BackgroundImageLayout = ImageLayout.Zoom
                        p.Cursor = Cursors.Hand
                        AddHandler p.Click, Sub()
                                                If Not CHAT.chat_aktiv Then MsgBox("Chat inaktiv!") : Exit Sub
                                                If CHAT IsNot Nothing Then
                                                    saveEmoji(aa)
                                                End If
                                            End Sub

                        FlowLayoutPanel.Controls.Add(p)
                    End If
                End If
                'MsgBox(a)
            Next
        End If
    End Sub

    'Sub initEmojisTEST()
    '    FlowLayoutPanel.Controls.Clear()
    '    If alloweasteregg Then pic.Visible = False

    '    If IO.Directory.Exists(DATENVERVER_OPTIONS.getRootDir & "\DOKUMENTE\CHAT_EMOJIS\") Then
    '        Dim EmojiPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "CHAT_EMOJIS\"
    '        If Not IO.Directory.Exists(EmojiPath) Then IO.Directory.CreateDirectory(EmojiPath)

    '        If VERAG_PROG_ALLGEMEIN.cProgrammeUpdate.copyProgramLIST(DATENVERVER_OPTIONS.getRootDir & "\DOKUMENTE\CHAT_EMOJIS\", EmojiPath, {}) Then
    '            For Each a In IO.Directory.GetFiles(EmojiPath) '.OrderBy(Function(f) f)
    '                If alloweasteregg Or Not a.Contains("easteregg") Then
    '                    If IO.File.Exists(a) And a.Contains(".png") And a.Contains("emoji_") Then

    '                        Dim p As New PictureBox
    '                        p.Size = New Size(40, 40)
    '                        p.BackgroundImage = Image.FromFile(a)
    '                        p.BackgroundImageLayout = ImageLayout.Zoom
    '                        p.Cursor = Cursors.Hand
    '                        AddHandler p.Click, Sub()
    '                                                If Not CHAT.chat_aktiv Then MsgBox("Chat inaktiv!") : Exit Sub
    '                                                If CHAT IsNot Nothing Then
    '                                                    saveEmoji(a)
    '                                                End If
    '                                            End Sub

    '                        FlowLayoutPanel.Controls.Add(p)
    '                    End If
    '                End If
    '            Next
    '        End If
    '    End If
    'End Sub

    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 chat_name LIKE '%" & MyTextBox1.Text.Trim & "%' "
            End If

            .DataSource = SQL.loadDgvBySql("SELECT  * FROM(
                                                SELECT [chat_id],CASE WHEN chat_name<>'' THEN chat_name ELSE (SELECT TOP 1 mit_vname + ' ' + mit_nname FROM tblMessenger_ChatMembers INNER JOIN tblMitarbeiter ON mit_id=chatMb_maId where chatMb_chatId=chat_id AND chatMb_maId <>" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & ") END as chat_name 
                                               ,(SELECT REPLACE(COUNT(*),'0','') FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE [chat_id]=chatMg_chatId AND chatMgSt_MaId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & " AND chatMgSt_gelesen=0)  as ungelesen ,chat_lastMsg
                                                FROM [tblMessenger_Chat] WHERE (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId=chat_id AND chatMB_maId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & ")>0
                                                AND chat_aktiv='" & (Not cbxInaktiveChats.Checked) & "'
                                            ) as T  " & whereName & " ORDER BY chat_lastMsg DESC", "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("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


                If Not reloadChat Then
                    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
                Else

                    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 If
            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 dgvChats_SelectionChanged(sender As Object, e As EventArgs) Handles dgvChats.SelectionChanged
        If Not loaded Then Exit Sub
        topMessagesDateHistory = Nothing ' zurücksetzen des HistoryDate
        MyFlowLayoutPanel1.Controls.Clear()
        If dgvChats.SelectedRows.Count > 0 Then
            CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(dgvChats.SelectedRows(0).Cells("chat_id").Value, topMessages, topMessagesDateHistory)
            SplitContainer1.Enabled = True
            RELOAD_CHAT()
        End If
    End Sub

    Sub RELOAD_CHAT()
        Try
            lblChatName.Text = "-"
            '    Dim scrollMax = (MyFlowLayoutPanel1.VerticalScroll.Value = MyFlowLayoutPanel1.VerticalScroll.Maximum)
            MyFlowLayoutPanel1.Controls.Clear()
            If CHAT IsNot Nothing Then
                CHAT.READ_ALL_MESSAGES()
                '  CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(dgvChats.SelectedRows(0).Cells("chat_id").Value)
                For Each MSG In CHAT.CHAT_MESSAGES
                    MyFlowLayoutPanel1.Controls.Add(getControlFromMSG(MSG))
                Next
                '  MyFlowLayoutPanel1.VerticalScroll.()
                'MyFlowLayoutPanel1.AutoScrollPosition = New Point(MyFlowLayoutPanel1.Width, MyFlowLayoutPanel1.Height)
                '  If MyFlowLayoutPanel1.Controls.Count > 0 Then MyFlowLayoutPanel1.ScrollControlIntoView(MyFlowLayoutPanel1.Controls(MyFlowLayoutPanel1.Controls.Count - 1))

                '  If scrollMax Then
                MyFlowLayoutPanel1.VerticalScroll.Value = MyFlowLayoutPanel1.VerticalScroll.Maximum

                If CHAT.chat_name <> "" Then
                    lblChatName.Text = CHAT.chat_name
                    Button5.BackgroundImage = My.Resources.people
                Else
                    lblChatName.Text = SQL.getValueTxtBySql("SELECT isnull(mit_vname,'') + ' ' + isnull(mit_nname,'')  FROM [tblMessenger_ChatMembers] inner join tblMitarbeiter on mit_id=chatMb_maId where chatMb_chatId ='" & CHAT.chat_id & "'  and chatMb_maId<>'" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "'", "ADMIN")
                    Button5.BackgroundImage = My.Resources.person
                End If
            End If
            checkOnlineOffline()
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub


    Sub checkOnlineOffline()
        Try

            If CHAT Is Nothing OrElse CHAT.chat_name <> "" Then
            lblOnlineOffline.Visible = False
        Else
                lblOnlineOffline.Visible = True
                Dim cntOnline = SQL.getValueTxtBySql("SELECT count(*) FROM [tblMessenger_ChatMembers] inner join tblSessions  ON sess_maId=[chatMb_maId] and sess_lastRm > dateadd(MINUTE,-2, getdate()) where chatMb_chatId ='" & CHAT.chat_id & "' and chatMb_maId<>'" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "'", "ADMIN")
                If cntOnline > 0 Then
                lblOnlineOffline.Text = "ONLINE"
                lblOnlineOffline.BackColor = Color.MediumSeaGreen
            Else
                lblOnlineOffline.Text = "OFFLINE"
                lblOnlineOffline.BackColor = Color.Red
            End If
        End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub

    Function getControlFromMSG(MSG As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages)
        Select Case MSG.chatMg_type
            Case "TEXT"

                Dim CHAT_ITEM As New usrCntlMessenger_ChatElement(MSG)
                checkUsrId(MSG, CHAT_ITEM)

                'CHAT_ITEM.txtChatmessage.Text = MSG.chatMg_text
                'CHAT_ITEM.lblName.Text = MSG.chatMg_maId
                Return (CHAT_ITEM)



                        'CHAT.READ_ALL_MESSAGES()

            Case "ATTACHMENT"


                Dim CHAT_ITEM As New usrCntlMessenger_ChatAnhang(MSG)
                checkUsrId(MSG, CHAT_ITEM)
                '   CHAT_ITEM.path = MSG.chatMg_text
                ' CHAT_ITEM.txtChatmessage.Text = MSG.chatMg_text
                'CHAT_ITEM.lblName.Text = MSG.chatMg_maId
                Return (CHAT_ITEM)

            Case "EMOJI"


                Dim CHAT_ITEM As New usrCntlMessenger_ChatEmoji(Me, MSG)
                checkUsrId(MSG, CHAT_ITEM)
                '   CHAT_ITEM.path = MSG.chatMg_text
                ' CHAT_ITEM.txtChatmessage.Text = MSG.chatMg_text
                'CHAT_ITEM.lblName.Text = MSG.chatMg_maId
                Return (CHAT_ITEM)
            Case "DEL_TEXT", "DEL_ATTACHMENT", "DEL_EMOJI"

                Dim CHAT_ITEM As New usrCntlMessenger_ChatElementDEL(MSG)
                checkUsrId(MSG, CHAT_ITEM)
                Return (CHAT_ITEM)
        End Select
        Return Nothing
    End Function

    Sub REFRESH_CHAT()
        Try

            If CHAT IsNot Nothing Then
                CHAT.LOAD_MESSAGES(topMessages)

                '  CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(dgvChats.SelectedRows(0).Cells("chat_id").Value)
                Dim newMsg As Boolean = False
                For Each MSG In CHAT.CHAT_MESSAGES
                    Dim found As Boolean = False
                    For Each I In MyFlowLayoutPanel1.Controls
                        Select Case I.GetType.ToString
                            Case GetType(usrCntlMessenger_ChatElement).ToString
                                If DirectCast(I, usrCntlMessenger_ChatElement).CHAT_MSG.chatMg_id = MSG.chatMg_id Then
                                    found = True
                                End If
                            Case GetType(usrCntlMessenger_ChatAnhang).ToString
                                If DirectCast(I, usrCntlMessenger_ChatAnhang).CHAT_MSG.chatMg_id = MSG.chatMg_id Then
                                    found = True
                                End If
                            Case GetType(usrCntlMessenger_ChatEmoji).ToString
                                If DirectCast(I, usrCntlMessenger_ChatEmoji).CHAT_MSG.chatMg_id = MSG.chatMg_id Then
                                    found = True
                                End If
                            Case GetType(usrCntlMessenger_ChatElementDEL).ToString
                                If DirectCast(I, usrCntlMessenger_ChatElementDEL).CHAT_MSG.chatMg_id = MSG.chatMg_id Then
                                    found = True
                                End If
                        End Select

                    Next
                    If Not found Then
                        newMsg = True
                        MyFlowLayoutPanel1.Controls.Add(getControlFromMSG(MSG))

                        'Dim CHAT_ITEM As New usrCntlMessenger_ChatElement(MSG)
                        'checkUsrId(MSG, CHAT_ITEM)

                        ''CHAT_ITEM.txtChatmessage.Text = MSG.chatMg_text
                        ''CHAT_ITEM.lblName.Text = MSG.chatMg_maId
                        'MyFlowLayoutPanel1.Controls.Add(CHAT_ITEM)
                        CHAT.READ_ALL_MESSAGES()
                    End If
                Next
                If newMsg Then
                    MyFlowLayoutPanel1.VerticalScroll.Value = MyFlowLayoutPanel1.VerticalScroll.Maximum
                End If
                '  MyFlowLayoutPanel1.VerticalScroll.()
                'MyFlowLayoutPanel1.AutoScrollPosition = New Point(MyFlowLayoutPanel1.Width, MyFlowLayoutPanel1.Height)
                ' If MyFlowLayoutPanel1.Controls.Count > 0 Then MyFlowLayoutPanel1.ScrollControlIntoView(MyFlowLayoutPanel1.Controls(MyFlowLayoutPanel1.Controls.Count - 1))
                '        MyFlowLayoutPanel1.VerticalScroll.Value = MyFlowLayoutPanel1.VerticalScroll.Maximum --> nur, wenn neue MSG
            End If
            checkOnlineOffline()
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub

    'Sub ORDER_CHAT_MSG()
    '    If Not CHECK_CHATMSG_ORDER() Then

    '        For Each I As usrCntlMessenger_ChatElement In MyFlowLayoutPanel1.Controls

    '        Next
    '    End If

    'End Sub
    'Function CHECK_CHATMSG_ORDER() As Boolean
    '    Dim oldItem = Nothing
    '    For Each I As usrCntlMessenger_ChatElement In MyFlowLayoutPanel1.Controls
    '        If oldItem IsNot Nothing And I.CHAT_MSG.chatMg_datetime < oldItem.CHAT_MSG.chatMg_datetime Then
    '            Return False
    '        End If
    '        oldItem = I
    '    Next
    '    Return True
    'End Function
    Sub checkUsrId(MSG As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages, CHAT_ITEM As usrCntlMessenger_ChatElement)
        If MSG.chatMg_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then
            CHAT_ITEM.Margin = New Padding(MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30, 0, 0, 0)
            'CHAT_ITEM.Left = (MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30)
            'CHAT_ITEM.Anchor = AnchorStyles.None
            'CHAT_ITEM.Dock = DockStyle.Right
            ' CHAT_ITEM.Dock = DockStyle.Right
            CHAT_ITEM.setBgCOLOR(Color.FromArgb(192, 255, 192))
        End If
    End Sub
    Sub checkUsrId(MSG As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages, CHAT_ITEM As usrCntlMessenger_ChatElementDEL)
        If MSG.chatMg_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then
            CHAT_ITEM.Margin = New Padding(MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30, 0, 0, 0)
            'CHAT_ITEM.Left = (MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30)
            'CHAT_ITEM.Anchor = AnchorStyles.None
            'CHAT_ITEM.Dock = DockStyle.Right
            ' CHAT_ITEM.Dock = DockStyle.Right
            ' CHAT_ITEM.setBgCOLOR(Color.FromArgb(192, 255, 192))
        End If
    End Sub
    Sub checkUsrId(MSG As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages, CHAT_ITEM As usrCntlMessenger_ChatEmoji)
        If MSG.chatMg_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then
            CHAT_ITEM.Margin = New Padding(MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30, 0, 0, 0)
            'CHAT_ITEM.Left = (MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30)
            'CHAT_ITEM.Anchor = AnchorStyles.None
            'CHAT_ITEM.Dock = DockStyle.Right
            ' CHAT_ITEM.Dock = DockStyle.Right
            CHAT_ITEM.setBgCOLOR(Color.FromArgb(192, 255, 192))
        End If
    End Sub
    Sub checkUsrId(MSG As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages, CHAT_ITEM As usrCntlMessenger_ChatAnhang)
        If MSG.chatMg_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then
            CHAT_ITEM.Margin = New Padding(MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30, 0, 0, 0)
            'CHAT_ITEM.Left = (MyFlowLayoutPanel1.Width - CHAT_ITEM.Width - 30)
            'CHAT_ITEM.Anchor = AnchorStyles.None
            'CHAT_ITEM.Dock = DockStyle.Right
            ' CHAT_ITEM.Dock = DockStyle.Right
            CHAT_ITEM.setBgCOLOR(Color.FromArgb(192, 255, 192))
        End If

    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        If Not CHAT.chat_aktiv Then MsgBox("Chat inaktiv!") : Exit Sub
        If rtbChatMessage.Text.Trim <> "" Then
            If CHAT IsNot Nothing Then

                Dim MSG As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
                MSG.chatMg_text = rtbChatMessage.Text.Trim
                MSG.chatMg_maName = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.Fullname
                MSG.chatMg_maFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

                If MSG.SAVE(True, CHAT.CHAT_MEMBERS) Then
                    SEND_TOKEN_NEW_MESSAGE()
                    ' CHAT.CHAT_MESSAGES.Add(MSG)
                    SET_ALL_READ()
                    REFRESH_CHAT()
                    rtbChatMessage.Text = ""
                    rtbChatMessage.Focus()
                End If

            End If
        End If
    End Sub

    Sub SET_ALL_READ()
        For Each u In MyFlowLayoutPanel1.Controls
            Select Case u.GetType.ToString
                Case GetType(usrCntlMessenger_ChatElement).ToString
                    DirectCast(u, usrCntlMessenger_ChatElement).lblNewMsg.Visible = False
                Case GetType(usrCntlMessenger_ChatAnhang).ToString
                    DirectCast(u, usrCntlMessenger_ChatAnhang).lblNewMsg.Visible = False
                Case GetType(usrCntlMessenger_ChatEmoji).ToString
                    DirectCast(u, usrCntlMessenger_ChatEmoji).lblNewMsg.Visible = False
            End Select
        Next
    End Sub
    Sub SEND_TOKEN_NEW_MESSAGE()
        For Each MB In CHAT.CHAT_MEMBERS
            If MB.chatMb_maId <> VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then

                Dim IP = cSession.GET_IP_FROM_MAID(MB.chatMb_maId)

                If IP <> "" Then
                    Dim SC As New cServerClient                '                SC.begin("192.168.0.50", "NEW_MESSAGE") '192.168.0.95 = atlas suben
                    SC.begin(IP, "NEW_MESSAGE")
                    '   MsgBox(IP)
                End If
            End If
        Next

        'SC.waitTillFinished()
        'Thread.Sleep(1000)

        'If SC.status = "TaskSuccess" Then

        'Else

        'End If


    End Sub


    Private Sub rtbChatMessage_KeyDown(sender As Object, e As KeyEventArgs) Handles rtbChatMessage.KeyDown
        If e.Modifiers = Keys.Control And e.KeyCode = Keys.Return Then
            btn.PerformClick()
            e.Handled = True
        End If
    End Sub



    Private Sub TimerNEW_MESSAGE_Tick(sender As Object, e As EventArgs) Handles TimerNEW_MESSAGE.Tick
        If CHAT IsNot Nothing And VERAG_PROG_ALLGEMEIN.cMessenger.NEW_MESSGE = True Then
            VERAG_PROG_ALLGEMEIN.cMessenger.NEW_MESSGE = False
            ' MsgBox("asd")
            REFRESH_CHAT()
        End If
    End Sub

    Private Sub Timer_REFRESH_Tick(sender As Object, e As EventArgs) Handles Timer_REFRESH.Tick
        loaded = False
        REFRESH_CHAT()
        Dim dgv_ChatID = If(dgvChats.SelectedRows.Count > 0, dgvChats.SelectedRows(0).Cells("chat_id").Value, -1)
        If checkNewestShit() Then ' prüft, ob neue Nachrichten gekommen sind, sont kein Refresh (stört das scrollen)
            intiDGVChats(dgv_ChatID, False)
        End If

        loaded = True
    End Sub


    Function checkNewestShit() As Boolean
        Try

            Dim Dt_New As DataTable = SQL.loadDgvBySql("SELECT [chat_id],CASE WHEN chat_name<>'' THEN chat_name ELSE (SELECT TOP 1 mit_vname + ' ' + mit_nname FROM tblMessenger_ChatMembers INNER JOIN tblMitarbeiter ON mit_id=chatMb_maId where chatMb_chatId=chat_id AND chatMb_maId <>" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & ") END as chat_name 
                                          ,(SELECT REPLACE(COUNT(*),'0','') FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE [chat_id]=chatMg_chatId AND chatMgSt_MaId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & " AND chatMgSt_gelesen=0)  as ungelesen  
                                            FROM [tblMessenger_Chat] WHERE (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId=chat_id AND chatMB_maId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & ")>0
                                            AND chat_aktiv='" & (Not cbxInaktiveChats.Checked) & "' ORDER BY chat_lastMsg DESC", "ADMIN")
            Dim Dt_Current As DataTable = dgvChats.DataSource

            If Dt_Current.Rows.Count <> Dt_New.Rows.Count Then Return True

            For Each r As DataRow In Dt_New.Rows
                If r("ungelesen") IsNot DBNull.Value AndAlso r("ungelesen") <> "" AndAlso CInt(r("ungelesen")) > 0 Then
                    Return True
                End If
            Next

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Sub initMsg()
        Dim dgv_ChatID = If(dgvChats.SelectedRows.Count > 0, dgvChats.SelectedRows(0).Cells("chat_id").Value, -1)
        'intiDGVChats(dgv_ChatID)
    End Sub

    Private Sub frmMessenger_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        dgvChats.ClearSelection()
        SplitContainer1.Enabled = False
        loaded = True
    End Sub

    Private Sub cbxInaktiveChats_CheckedChanged(sender As Object, e As EventArgs) Handles cbxInaktiveChats.CheckedChanged
        intiDGVChats()
        If sender.checked Then
            ChatDeaktivierenToolStripMenuItem.Text = "Chat aktivieren"
        Else
            ChatDeaktivierenToolStripMenuItem.Text = "Chat deaktivieren"
        End If
    End Sub

    Private Sub ChatDeaktivierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChatDeaktivierenToolStripMenuItem.Click
        If dgvChats.SelectedRows.Count > 0 Then
            If vbYes = MsgBox("Möchten Sie diesen Chat wirklich deaktivieren?", vbYesNoCancel) Then

                CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(dgvChats.SelectedRows(0).Cells("chat_id").Value, 1)
                SplitContainer1.Enabled = True
                CHAT.chat_aktiv = Not CHAT.chat_aktiv
                CHAT.SAVE(False)

                intiDGVChats()
            End If
            'RELOAD_CHAT()
        End If
    End Sub

    'Private Sub dgvChats_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvChats.CellValueChanged
    '    Try

    '        If dgvChats.Columns.Count > 0 Then

    '            If e.ColumnIndex = dgvChats.Columns("ungelesen").Index Then
    '                If dgvChats.Rows(e.RowIndex).Cells("ungelesen").Value <> "" Then
    '                    dgvChats.Rows(e.RowIndex).Cells("ungelesen").Style.BackColor = Color.Red
    '                End If
    '                '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

    '                '    If r.Cells("ungelesen").Value <> "" Then
    '                '        r.Cells("ungelesen").Style.BackColor = Color.Red
    '                '    End If
    '                'Next
    '            End If
    '        End If

    '    Catch ex As Exception
    '        MsgBox(ex.Message & ex.StackTrace)
    '    End Try
    'End Sub

    Private Sub dgvChats_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles dgvChats.CellPainting
        Try

            If dgvChats.Columns.Count > 0 Then

                If e.ColumnIndex = dgvChats.Columns("ungelesen").Index Then
                    If dgvChats.Rows(e.RowIndex).Cells("ungelesen").Value <> "" Then
                        dgvChats.Rows(e.RowIndex).Cells("ungelesen").Style.BackColor = Color.Red
                    End If
                    '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

                    '    If r.Cells("ungelesen").Value <> "" Then
                    '        r.Cells("ungelesen").Style.BackColor = Color.Red
                    '    End If
                    'Next
                End If
            End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If Not CHAT.chat_aktiv Then MsgBox("Chat inaktiv!") : Exit Sub
        If CHAT IsNot Nothing Then
            Dim fd As New OpenFileDialog
            '  fd.Filter = "Excel Dateien|*.xls;*.xlsx"
            fd.RestoreDirectory = True
            fd.Title = "Datei auswählen"

            ' fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

            'fd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
            'fd.FilterIndex = 2

            If fd.ShowDialog() = System.Windows.Forms.DialogResult.OK And fd.FileName <> "" Then
                saveFileAtt(fd.FileName)
                'Dim fileName = New IO.FileInfo(fd.FileName).Name
                'Dim docId = -1
                'If saveToDS(fileName, fd.FileName, docId) Then

                '    Dim MSG As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
                '    MSG.chatMg_type = "ATTACHMENT"
                '    MSG.chatMg_text = fileName
                '    MSG.chatMg_anhang_docId = docId
                '    MSG.chatMg_maName = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.Fullname
                '    MSG.chatMg_maFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

                '    If MSG.SAVE(True, CHAT.CHAT_MEMBERS) Then
                '        SEND_TOKEN_NEW_MESSAGE()
                '        ' CHAT.CHAT_MESSAGES.Add(MSG)
                '        SET_ALL_READ()
                '        REFRESH_CHAT()
                '        rtbChatMessage.Text = ""
                '        rtbChatMessage.Focus()
                '    End If
                ' End If
            End If

        End If
    End Sub

    Sub saveFileAtt(filePath)
        Dim fileName = New IO.FileInfo(filePath).Name
        Dim docId = -1
        If saveToDS(fileName, filePath, docId) Then

            Dim MSG As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
            MSG.chatMg_type = "ATTACHMENT"
            MSG.chatMg_text = fileName
            MSG.chatMg_anhang_docId = docId
            MSG.chatMg_maName = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.Fullname
            MSG.chatMg_maFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

            If MSG.SAVE(True, CHAT.CHAT_MEMBERS) Then
                SEND_TOKEN_NEW_MESSAGE()
                ' CHAT.CHAT_MESSAGES.Add(MSG)
                SET_ALL_READ()
                REFRESH_CHAT()
                rtbChatMessage.Text = ""
                rtbChatMessage.Focus()
            End If
        End If
    End Sub
    Sub saveEmoji(filePath)
        '  Dim fileName = New IO.FileInfo(filePath).Name
        'Dim docId = -1
        'If saveToDS(fileName, filePath, docId) Then

        Dim MSG As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMessages(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
        MSG.chatMg_type = "EMOJI"
        MSG.chatMg_text = filePath
        'MSG.chatMg_anhang_docId = docId
        MSG.chatMg_maName = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.Fullname
        MSG.chatMg_maFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

        If MSG.SAVE(True, CHAT.CHAT_MEMBERS) Then
            SEND_TOKEN_NEW_MESSAGE()
            ' CHAT.CHAT_MESSAGES.Add(MSG)
            SET_ALL_READ()
            REFRESH_CHAT()
            'rtbChatMessage.Text = filePath
            'rtbChatMessage.Focus()
        End If
        '  End If
    End Sub
    Public Shared Function saveToDS(fileName, sourcePath, Optional ByRef da_id = -1) As Boolean
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "CHAT_ANHAENGE", Now.ToString("ddMMyy_HHmmss.ffff"), "", "", fileName, -1, False)
        If Not DS.uploadDataToDATENSERVER(sourcePath) Then MsgBox("Fehler beim Speichern: Datenserver!") : Return False
        If DS.da_id <= 0 Then MsgBox("Keine DocId!") : Return False
        da_id = DS.da_id
        ' destPath = DS.GET_TOP1_PATH
        Return True
    End Function


    Private Sub dgvChats_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvChats.CellMouseClick
        If e.Button = MouseButtons.Right Then

            If e.RowIndex >= 0 Then
                If dgvChats.Rows.Count > 0 Then

                    'Dim chatId = dgvChats.Rows(e.RowIndex).Cells("chat_id").Value
                    'VERAG_PROG_ALLGEMEIN.cMessenger.GEN_NEW_CHAT()
                    dgvChats.ClearSelection()
                    SplitContainer1.Enabled = False
                    CHAT = Nothing
                End If
                dgvChats.Rows(e.RowIndex).Selected = True
                cntxt.Show(Cursor.Position)
            End If
        End If
    End Sub




    Private Sub Form1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles rtbChatMessage.DragEnter ', txt.DragEnter, Me.DragEnter, picPDF.DragEnter
        e.Effect = DragDropEffects.All
    End Sub
    Private Sub txt_Click(sender As Object, e As DragEventArgs) Handles rtbChatMessage.DragDrop ', txt.DragDrop, Me.DragDrop, picPDF.DragDrop
        Try
            If e.Data.GetDataPresent("FileDrop", True) = True Then
                Dim FileList As String() = CType(e.Data.GetData("FileDrop"), Object) 'Hier wird der Variable "Wert" das übergeben, was wir auf die Form gezogen haben. Bei einer Datei wäre es dann der Pfad der Datei.
                If FileList.Count > 0 Then
                    'If Not _MULTI_FILES And FileList.Count > 1 Then
                    '    MsgBox("Es können nicht mehrere Dateien hochgeladen werden!")
                    '    Exit Sub
                    'End If
                    For Each W In FileList
                        If Not W.ToUpper.EndsWith(".EXE") Then
                            saveFileAtt(W)
                        End If
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox("   FEHLER: DragDrop!" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Private Sub pic_Click(sender As Object, e As EventArgs) Handles pic.Click
        Dim codewort = InputBox("Whoami?", "¿").ToLower
        If codewort = "easteregg" Or codewort = "osterhase" Then
            cMitarbeiter.UPDATE_EASTEREGG(True)
            cAllgemein.MITARBEITER.LOAD(cAllgemein.USRID)

            alloweasteregg = True
            initEmojis()
            MsgBox("Hurra! Neue Emojis freigeschaltet!")
        End If
    End Sub

    Private Sub pic_MouseHover(sender As Object, e As EventArgs) Handles pic.MouseEnter
        pic.BackgroundImage = My.Resources.easteregg
    End Sub

    Private Sub pic_MouseLeave(sender As Object, e As EventArgs) Handles pic.MouseLeave
        pic.BackgroundImage = Nothing

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If CHAT Is Nothing Then Exit Sub

        If CHAT.chat_name <> "" Then
            Dim f As New frmMessenger_Members(CHAT)
            f.ShowDialog(Me)
        Else
            Dim mit_id = SQL.getValueTxtBySql("SELECT mit_id FROM [tblMessenger_ChatMembers] inner join tblMitarbeiter on mit_id=chatMb_maId where chatMb_chatId ='" & CHAT.chat_id & "'  and chatMb_maId<>'" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "'", "ADMIN")
            Dim f As New frmMitarbeitersuche(mit_id)
            f.ShowDialog(Me)
        End If

    End Sub

    Private Sub MyTextBox1_TextChanged(sender As Object, e As EventArgs) Handles MyTextBox1.Leave
        intiDGVChats(, False, True)
    End Sub

    Private Sub MyTextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyTextBox1.KeyUp
        If e.KeyCode = Keys.Return Or MyTextBox1.Text = "" Then
            intiDGVChats(, False, True)
        End If
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        MyTextBox1.Text = ""
        intiDGVChats(, False, True)
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim dateTmp = InputBox("Bitte geben Sie das Datum ein, ab dem der Chat dargestellt werden soll:",, Now.AddMonths(-1).ToShortDateString)
        If IsDate(dateTmp) Then
            topMessagesDateHistory = CDate(dateTmp)
            CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(dgvChats.SelectedRows(0).Cells("chat_id").Value, 1, topMessagesDateHistory)
            RELOAD_CHAT()
        Else
            MsgBox("Datum ungültig!")
        End If
    End Sub



    'Private Sub rtbChatMessage_TextChanged(sender As Object, e As EventArgs) Handles rtbChatMessage.TextChanged
    '    FlowLayoutPanel.Enabled = (rtbChatMessage.Text = "")
    'End Sub
End Class