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 {
        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 {
        console.log(req.query.roomId)
        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
    const roomId = req.query.roomId
    let leaveTime = ''
    console.log('서버에서 초기 leaveInfo',leaveInfo)
    for (let i = 1; i < leaveInfo.length; i++) {    //일단 형식좀 맞추고
        leaveInfo[i] = JSON.parse(leaveInfo[i])
    }

    //findOne으로 해보자
    for (let i = 1; i <= leaveInfo.length - 1; i++) {   //그 방의 id와 나간기록의 방과 일치하는지 확인하고
        if (leaveInfo[i].roomName === roomId) {
            leaveTime = leaveInfo[i].leaveTime  //그 방에서 나간 시간을 찾아옴
            break;
        }
    }

    const room_id = await Room.find({ roomId: roomId }).select('_id')   //id로 _id를 찾아와서
    let unreadMsg = await Chat.find({ room: room_id }).select('createdAt')  //그 방의 메세지와 전송시간을 가져옴
    let count = 0
    //mongoose 시간비교 방법이 있음 (gte...)
    for (let i = 0; i <= unreadMsg.length - 1; i++) {
        const dbtime = Date.parse(unreadMsg[i].createdAt)
        const parsedleaveTime = Date.parse(leaveTime)
        if (parsedleaveTime < dbtime) {         //시간 비교를하고 이후에 온 메세지의 개수를 count함
            console.log('이번째부터 나중에온 메세지', i)
            count += 1
        }
    }
    res.json(count)
}

const dbChat = async (req, res) => {
    const roomId = req.query.roomId
    const room_id = await Room.find({ roomId: roomId }).select('_id')
    let chatlist = await Chat.find({ room: room_id }).select('message')
    res.json(chatlist)
}

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