import React, { useState, useEffect, useRef } from 'react'
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr'

import ChatWindow from './chat/ChatWindow.component'
import ChatInput from './chat/ChatInput.component'

const NotificationListComponent = () => {
    const [ connection, setConnection ] = useState(null)
    const [ chat, setChat ] = useState([])
    const latestChat = useRef(null)

    latestChat.current = chat
    const userId =  "dfdf19e4-8dde-4e4a-a3ea-5560b69d702b"

    useEffect(() => {
        const newConnection = new HubConnectionBuilder()
            .withUrl(`/api/MettaNotificationHub?userId=${userId}`)
            .configureLogging(LogLevel.Information)
            // .withUrl('/api/chatHub')
            .withAutomaticReconnect()
            .build()

        setConnection(newConnection)
    }, [])

    useEffect(() => {
        if (connection) {
            connection.start()
                .then(result => {
                    console.log('Connected!')
                    getConnectionInfo()
                    // connection.on('ReceiveMessage', message => {
                    connection.on('ReceiveMettaNotification', message => {
                        console.log('received from server: ',message)
                        // console.log(`received from server: ${message}`)
                        // const updatedChat = [...latestChat.current]
                        // updatedChat.push(message)
                    
                        // setChat(updatedChat)
                    })
                })
                .catch(e => console.log('Connection failed: ', e))
            
            connection.onclose( () => {
              console.log('reconnecting in 5 secs ...')
            })
        }
    }, [connection])

    const getConnectionInfo = async () => {
        if (connection.connectionStarted) {
            try {
                const connectionId = await  connection.invoke('GetConnectionId');
                // await  connection.invoke('PushNotification', user, message);
                // await  connection.send('SendMessage', chatMessage)
                console.log('connection Id = ',connectionId)
            }
            catch(e) {
                console.log(e)
            }
        }
        else {
            alert('No connection to server yet.')
        }
    }

    const sendMessage = async (user, message) => {
        
        if (connection.connectionStarted) {
            try {
                await  connection.invoke('SendMessage', user, message);
                // await  connection.invoke('PushNotification', user, message);
                // await  connection.send('SendMessage', chatMessage)
            }
            catch(e) {
                console.log(e)
            }
        }
        else {
            alert('No connection to server yet.')
        }
    }

    return (
        <div>
            <ChatInput sendMessage={sendMessage} />
            <hr />
            <ChatWindow chat={chat}/>
        </div>
    )
}

export default NotificationListComponent