import React, { useState, useEffect } from 'react'
import { Badge, ListGroup } from 'react-bootstrap';
import "../Pages/Home.css";
import axios from 'axios'
import catchErrors from '../utils/catchErrors';


function ClosedList(props) {
  const [error, setError] = useState('')
  const realTime = new Date().toISOString()

  async function recordEntryLog(e) {
    const leaveInfo = { userId: props.userId, roomCode: e.target.name, leaveTime: realTime }
    try {
      const check = await axios.get('/room/entrylog', { params: leaveInfo })
      if (check.data) {       //있으면 put으로
        await axios.put('/room/entrylog', leaveInfo)
      } else {        //없으면 post
        await axios.post('/room/entrylog', leaveInfo)
      }
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  async function enterChatRoomCH(e) {
    if (props.roomCode) {
      props.closeChatRoom(props.roomCode)
    }
    const roomCode = e.target.name
    const roomName = e.target.value
    props.enterChatRoom(roomCode)
    props.setRoomCode(roomCode)
    props.setRoomName(roomName)

    await recordEntryLog(e) //방 입장시 시간 업데이트 (그래야 안 읽은 메세지가 0개로  되니까)
    props.unreadMessage() //방 입장시 메세지 개수 다시셈 (그래야 입장시 0으로 초기화 되니까)

  }

  //안읽은 메세지 count하는 부분

  useEffect(() => { // 누군가 보내면 다시 개수 셈
    console.log('chat 클라이언트 변경!')
    props.unreadMessage()
    console.log('새 메세지가 도착했습니다.', props.leftInfo)
  }, [props.checknew])

  useEffect(() => { //일단 들오면 실행해야지
    props.unreadMessage()
  }, [props.closedlist])



  let count = []
  const [unread, setUnread] = useState([])
  useEffect(() => { //unread정보가 들어오면 재정비해서 뿌려주기 위한 작업!
    for (let i = 0; i < props.unreadnumber.length; i++) {
      count.push(props.unreadnumber[i].unreadcount)
    }
    setUnread(count)
  }, [props.unreadnumber])

  return (
    <div style={{height: "80vh"}}>
    <div style={{overflow: 'auto', height:"100%"}}>
      {props.closedlist.map((item, index) =>
        <ListGroup key={index}>
          <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}
            className='rounded-0'>
            {item.roomName}
            {unread[index] ? <Badge className='ml-2' pill variant='danger'>{unread[index]}</Badge> : ''}
          </ListGroup.Item>
        </ListGroup>
      )
      }
    </div >
    </div>
  )
}

export default ClosedList