import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'
import Chat from "../models/Chat.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 {
        console.log('req확인', req.query._id)
        let list = await Room.find({ member: req.query._id })
        // console.log('c_list가져오기', list)
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

const getOpenList = async (req, res) => {
    try {
        let list = await Room.find({ isOpen: true })
        // console.log('o_list가져오기', list)
        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)
        }
        res.end()
    } catch (error) {
        res.status(500).send('멤버 업데이트 실패')
    }
}

const roomInf = async (req, res) => {
    try {
        console.log(req.query.roomId)
        // let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec()
        let roomInf = await Room.find({ roomId: req.query.roomId })
        console.log('room_member로 정보 가져오기:', roomInf)
        return res.json(roomInf)
    } catch (error) {
        alert('올바르지 못한 접근입니다.')
    }
}

// const unreadMessage = async (req, res) => {
//     let leaveInfo = req.query.leaveInfo
//     // leaveInfo.shift()
//     const roomId = req.query.roomId
//     let leaveTime = ''
//     for (let i = 1; i < leaveInfo.length - 1; i++) {    //일단 형식좀 맞추고
//         leaveInfo[i] = JSON.parse(leaveInfo[i])
//     }


//     for (let i = 1; i <= leaveInfo.length - 1; i++) {   //그 방의 id와 나간기록의 방과 일치하는지 확인하고
//         if (leaveInfo[i].roomName === roomId) {
//             leaveTime = leaveInfo[i].leaveTime  //그 방에서 나간 시간을 찾아옴
//             console.log('서버의 포문', i, leaveTime)
//             break;
//         }
//     }
//     // console.log('서버에서 unreadMessage', leaveInfo, roomId)
//     const room_id = await Room.find({ roomId: roomId }).select('_id')   //id로 _id를 찾아와서
//     let unreadMsg = await Chat.find({ room: room_id }).select('message createdAt')  //그 방의 메세지와 전송시간을 가져옴
//     // console.log('서버에서 두번재 언리드', unreadMsg)
//     console.log('서버에서 언리드', leaveTime)
//     let count = 0
//     for (let i = 0; i <= unreadMsg.length - 1; i++) {
//         const dbtime = Date.parse(unreadMsg[i].createdAt)
//         const parsedleaveTime = Date.parse(leaveTime)
//         if (parsedleaveTime > dbtime) {
//             console.log('이번째부터 나중에온 메세지', i)
//             count += 1
//         }
//     }
//     console.log('카운트 세버', count)
//     return count
// }

// const dbChat = async (req, res) => {
//     const chatlist = await Chat
//     console.log(chatlist)

// }

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