import React, { useState, useEffect } from 'react'
import { Badge, Button, ListGroup } from 'react-bootstrap';
import axios from 'axios'

const INIT_LIST = [{
  interest: '',
  isOpen: '',
  memeber: [],
  roomId: '',
  roomName: '',
}]
function ClosedList(props) {

  const [list, setList] = useState(INIT_LIST);

  useEffect(() => {
    getClosedList();
  }, [props.roomCode]);


  async function getClosedList() {
    const userid = sessionStorage.getItem('userId')
    let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
    setList(res.data)
  }

  const realTime = new Date().toISOString()

  function enterChatRoomCH(e) {
    const roomCode = e.target.name
    const roomName = e.target.value
    props.enterChatRoom(roomCode)
    props.setRoomCode(roomCode)


console.log('1111111111111111111',props.leaveInfo, typeof(props.leaveInfo))
  }



  const [checknew, setChecknew] = useState([])
  const [unreadnumber, setUnreadnumber] = useState([''])
  async function dbChat() {
    for (let i = 0; i <= list.length - 1; i++) {
      const respond = await axios.get('/room/dbChat', { params: { 'roomId': list[i].roomId } })
      setChecknew(respond.data)
    }
  }
  useEffect(() => {
    dbChat()
  }, [props.singleChat, props.recievedMsg])

  useEffect(() => {
    // console.log('chat 클라이언트 변경!')
    unreadMessage()
  }, [checknew])

  async function unreadMessage() {
    //여기서 나간시간과 db의 메세지와 시간비교해서 개수를 count해주면 됨
    //물론 그 방 별로 찾아서 list를 맵써서 하던?
    // console.log('ddddddddd', list[0].roomId)

    setUnreadnumber([''])
    let arr = []
    for (let i = 0; i <= list.length - 1; i++) {
      const respond = await axios.get('/room/unreadMessage', { params: { 'leaveInfo': props.leaveInfo, 'roomId': list[i].roomId } })
      // setUnreadnumber([...unreadnumber, respond.data])
      arr = [...arr, respond.data]
    }
    setUnreadnumber(arr)
    // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length)

  }


  return (
    <div>
      {list.map((item, index) =>
        <ListGroup key={index}>
          <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}>
            {item.roomName}
            {unreadnumber[index] ? <Badge className='ml-2' pill variant='danger'>{unreadnumber[index]}</Badge> : ''}
          </ListGroup.Item>
        </ListGroup>
      )}
    </div>
  )
}

export default ClosedList
