import express from 'express'
import connectDb from './utils/connectDb.js'
import userRouter from './routes/user.routes.js'
import authRouter from './routes/auth.routes.js'
import roomRouter from './routes/room.routers.js'
import roomEnterRouter from './routes/roomEnter.routers.js'
import bodyParser from "body-parser";
import http from "http";
import { Server } from 'socket.io';
import cors from "cors"
import Room from './models/Room.js'
import Chat from "./models/Chat.js"
import User from "./models/User.js"
import AccessInfo from "./models/AccessInfo.js"

connectDb()

const app = express()

const server = http.createServer(app);

const io = new Server(server)

io.on("connection", (socket) => { // 기본 연결
  console.log("socket connect ok", socket.id)

  socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
    console.log('join_data확인', data)
    let roomInfo = data;
    socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
  });

  // socket.on('access', async (data) => {
  //   console.log('access', data)
  //   const nick = await User.findOne({ _id: data.userInfo }).select('nickname').exec()
  //   const room = await Room.findOne({ roomId: data.rmIf })
  //   console.log('room확인2', room)
  //   //console.log('nick확인', nick) //{ _id: 5ffe897927a051f4bc17bbcc, nickname: 'rkyoung1' }
  //   const accessInfo = await new AccessInfo({
  //     room: room._id,
  //     userInfo: data.userInfo,
  //     nickname: nick.nickname,
  //     isEnt: true
  //   }).save()
  //   console.log('acc확인', accessInfo)
  // })

  socket.on('chat', async (data) => {
    console.log('roomname확인', data)
    const room = await Room.findOne({ roomId: data.roomInfo })
    console.log('room이 떴나', room)

    const chat = await new Chat({
      room: room._id,
      username: data.sendInfo.sender,
      message: data.sendInfo.msg
    }).save()
    console.log('resChat확인', chat)

    socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로
    console.log('broad cst실핼')
  });

  socket.on('disconnect', () => {
    console.log('disconnected from server id=', socket.id)
  })

});

app.use(bodyParser.json());
app.use(cors());

app.use('/images', express.static('uploads/'))
app.use(userRouter)
app.use(authRouter)
app.use(roomRouter)
app.use(roomEnterRouter)

server.listen(3030, () => {
  console.log('Listening on port 3030')
})

export default server
// module.exports = server;
