import {useState, useEffect} from 'react'
import {Table} from 'antd'

import LoaderPortal from '../../components/LoaderPortal'
import {invokeWebApiWrapperAsync} from '../../components/factory'
import {columns} from '../Messages'

import {Subscribe} from '../../services/signalr'
import {MessageService} from '../../services/api'
import '../../styles/message.css'

export default function ActiveMessagesOnline({idWell}) {
  const [messages, setMessages] = useState([])
  const [loader, setLoader] = useState(false)

  const handleReceiveMessages = (messages) => {
    if (messages) {
      setMessages(messages.items.splice(0, 4))
    }
  }

  useEffect(() => {
    invokeWebApiWrapperAsync(
    async () => {
        const messages = await MessageService.getMessages(idWell, 0, 4)
        handleReceiveMessages(messages)
      },
      setLoader,
      `Не удалось загрузить сообщения по скважине "${idWell}"`,
    )
    return Subscribe('hubs/telemetry','ReceiveMessages', `well_${idWell}`, handleReceiveMessages)
  }, [idWell])

  return (<LoaderPortal show={loader}>
    <Table
      showHeader={false}
      columns={columns}
      dataSource={messages}
      rowClassName={(record) => `event_message_${record.categoryId} event_message`}
      className={'message_table'}
      size={'small'}
      pagination={false}
      rowKey={(record) => record.id}
    />
  </LoaderPortal>)
}