import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'
import Chat from "../models/Chat.js"
import EntryLog from "../models/EntryLog.js"

const nanoid = customAlphabet('1234567890abcdef', 10)

const makeRoom = async (req, res) => {
    // console.log(req.body)
    const { roomName, interest, isOpen, member } = req.body;
    // console.log('콘솔확인', roomName, interest, isOpen, member)
    const roomId = nanoid()
    const room = await Room.findOne({ roomId })
    while (room) {
        roomId = nanoid()
        room = await Room.findOne({ roomId })
    }

    try {
        if (!isLength(roomName, { min: 3, max: 20 })) {
            return res.status(422).send('채팅방의 이름은 3-20자여야 합니다.')
        } else if (interest == 'Choose...' || interest == '') {
            return res.status(422).send('분야를 반드시 선택하여야 합니다.')
        }
        const newRoom = await new Room({
            roomId,
            roomName,
            interest,
            isOpen,
            member,
        }).save()
        // console.log(newRoom)
        res.json(newRoom)
    } catch (error) {
        console.log(error)
        res.status(500).send('방생성 에러')
    }
}

const getClosedList = async (req, res) => {
    try {
        let list = await Room.find({ member: req.query._id })
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

const getOpenList = async (req, res) => {
    try {
        let list = await Room.find({ isOpen: true })
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

const getRoomName = async (req, res) => {
    const roomId = req.query.roomCode
    // console.log('getRoomName', req.query.roomCode)

    try {
        let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
        // console.log(roominfo.roomName)
        return res.json(roominfo.roomName)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

const changemember = async (req, res) => {
    const { userId, roomId } = req.body
    // console.log(roomId)
    let room = await Room.findOne({ roomId: roomId }).select('member')
    const isPresent = room.member.indexOf(userId)
    try {
        if (isPresent < 0) {
            const memberId = room.member.push(userId)
            await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
            // console.log('room.member 업데이트 완료')
            return res.json(true)
        }
        else {
            return res.json(false)
        }
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

const deleteUserId = async (req, res) => {
    // console.log(req.body)
    const { userId, roomId } = req.body
    let room = await Room.findOne({ roomId: roomId }).select('member')
    // console.log('deletetest', room)
    const memIndex = room.member.indexOf(userId)
    try {
        room.member.splice(memIndex, 1)
        await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
        // console.log(`${roomId}방 ${userId}삭제완료`)
        return res.json(true)
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

const roomInf = async (req, res) => {
    try {
        let roomInf = await Room.find({ roomId: req.query.roomId })
        return res.json(roomInf)
    } catch (error) {
        alert('올바르지 못한 접근입니다.')
    }
}


const unreadMessage = async (req, res) => {
    const nowTime = new Date().toISOString()
    let leaveInfo = req.query
    try {
        for (const key in Object.keys(leaveInfo)) {
            leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
        }

        let countArr = []
        for (const key in Object.keys(leaveInfo)) {
            const room = await Room.findOne({ roomId: leaveInfo[key].roomCode })    //들어온 방 코드로 그 방의 정보 찾아옴
            const entrylog = await EntryLog.findOne({ userId: leaveInfo[key].userId, room: room._id }) //그 방에서 나간시간 가져옴
            if (entrylog) {
                if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                } else {
                    const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } })  //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
                    countArr.push({ roomCode: room.roomId, unreadcount: count.length })
                }
            } else {
                countArr.push(0)
            }
        }
        res.json(countArr)
    } catch (error) {
        res.send(error)
    }
}


export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, deleteUserId }
