Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useCallback, useEffect, useState } from 'react'
import { axios } from '../../utils'
import { Tab, Tabs } from '@mui/material'
import styled from 'styled-components'
import SearchIcon from '@mui/icons-material/Search'

import Contacts from './Contacts'
import ContactsModal from '../modals/ContactsModal'
import CreateGroupModal from '../modals/CreateGroupModal'

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

const StyledTab = styled(Tab)`
  flex-grow: 1;
  color: var(--subtitle-color) !important;
  font-weight: bold !important;
  padding: 0.5rem 1rem !important;
  min-height: auto !important;
  &.Mui-selected {
    color: var(--font-color) !important;
  }
`

const ChatContacts = ({ selectedConversation, changeConversation }) => {
  const [showContactModal, setShowContactModal] = useState(false)
  const [showGroupModal, setShowGroupModal] = useState(false)
  const [conversations, setConversations] = useState([])
  const [search, setSearch] = useState('')
  const [tab, setTab] = useState('user')

  const options = [
    {
      label: 'Iniciar conversación',
      action: () => setShowContactModal(!showContactModal)
    },
    { label: 'Crear grupo', action: () => setShowGroupModal(!showGroupModal) }
  ]

  const onCreateConversation = (url) => {
    const conversation = conversations.find((user) => user.url_send === url)
    changeConversation(conversation)
  }

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

      if (!success) {
        return
      }

      entities.map(
        (entity) =>
          entity.not_received_messages &&
          playNewMessage(entity.url_mark_received)
      )

      setConversations(entities)
    })
  }

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

  const getConversations = useCallback(
    () => conversations.filter((conversation) => conversation.type === tab),
    [tab, conversations]
  )

  const filterConversations = useCallback(
    (conversations) =>
      conversations.filter((conversation) =>
        conversation?.name?.toLowerCase().includes(search.toLowerCase())
      ),

    [search]
  )

  useEffect(() => {
    const heartBeatInterval = setInterval(() => heartBeat(), 3000)

    return () => {
      clearInterval(heartBeatInterval)
    }
  }, [])

  useEffect(() => {
    if (!selectedConversation) return

    const block = !conversations.some((c) => {
      return JSON.stringify(c) === JSON.stringify(selectedConversation)
    })

    if (block) {
      changeConversation(null)
    }
  }, [conversations, selectedConversation])

  return (
    <>
      <Contacts>
        <Contacts.Header options={options}>
          <h1>Chat</h1>
        </Contacts.Header>
        <Tabs
          value={tab}
          onChange={(e, newValue) => setTab(newValue)}
          sx={{
            width: '100%',
            minHeight: 'auto',
            '& .MuiTabs-indicator': {
              backgroundColor: 'var(--font-color)'
            }
          }}
        >
          <StyledTab label='Personas' value='user' disableRipple />
          <StyledTab label='Grupos' value='group' disableRipple />
        </Tabs>

        <div className='contact__search show'>
          <SearchIcon />
          <input
            type='text'
            placeholder='Buscar'
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        <Contacts.List
          contacts={filterConversations(getConversations())}
          onChange={changeConversation}
          currentConversation={selectedConversation}
        />
      </Contacts>
      <ContactsModal
        show={showContactModal}
        onClose={() => setShowContactModal(false)}
        onComplete={onCreateConversation}
      />
      <CreateGroupModal
        isOpen={showGroupModal}
        onClose={() => setShowGroupModal(false)}
      />
    </>
  )
}

export default ChatContacts