Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Autoría | Ultima modificación | Ver Log |

/* eslint-disable react/prop-types */
import React, { useEffect, useState } from 'react'
import { axios } from '../../utils'
import DesktopChat from '../templates/DesktopChat'
import MobileChat from '../templates/MobileChat'

const notifyAudio = new Audio('/audio/chat.mp3')

const Page = ({ backendVars }) => {
  const { timezones } = backendVars
  const [chatUsers, setChatUsers] = useState([])
  const [chatGroups, setChatGroups] = useState([])
  const [activeChat, setActiveChat] = useState(null)

  const heartBeat = async () => {
    axios.get('/chat/heart-beat').then(({ data: response }) => {
      const { data, success } = response
      if (success) {
        const entities = data
        let updatedChatUsers = []
        let updatedChatGroups = []

        entities.map(async (entity) => {
          if (entity.not_received_messages) {
            handlePlayNewMessage(entity.url_mark_received)
          }

          if (entity.is_open) {
            manageOpenConversations(entity)
          }

          switch (entity.type) {
            case 'user':
              updatedChatUsers = [...updatedChatUsers, entity]
              break
            case 'group':
              updatedChatGroups = [...updatedChatGroups, entity]
              break
            default:
              break
          }
        })
        setChatUsers(updatedChatUsers)
        setChatGroups(updatedChatGroups)
      }
    })
  }

  const manageOpenConversations = (entity) => {
    if (activeChat) {
      axios.post(entity.url_close)
      return
    }

    setActiveChat(entity)
  }

  const handlePlayNewMessage = async (setReceivedLink) => {
    notifyAudio.play()
    const { data } = await axios.post(setReceivedLink)
    return data.success
  }

  useEffect(() => {
    const heartBeatInterval = setInterval(heartBeat, 3000)
    heartBeat()
    return () => {
      clearInterval(heartBeatInterval)
    }
  }, [])

  return (
    <>
      {window.innerWidth >= 768 ? (
        <DesktopChat
          chatUsers={chatUsers}
          chatGroups={chatGroups}
          timezones={timezones}
        />
      ) : (
        <MobileChat
          chatGroups={chatGroups}
          chatUsers={chatUsers}
          timezones={timezones}
        />
      )}
    </>
  )
}

export default Page