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 bodyParser from "body-parser";
import http from "http";
import { Server } from 'socket.io';


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했을 때
    let roomName = data;
    console.log(roomName, "방 입장")
    socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴

  });

  socket.on('chat', (data) => {
    console.log(`chat실행 :`, data.roomName, data.msg)
    io.to(data.roomName).emit('broadcast', data.msg); //roomName에 존재하는 모든 소켓들에게 
  })

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


});

// app.use(express.json())
//이부분을 body 파싱함
app.use(bodyParser.json());

app.use(userRouter)
app.use(authRouter)
//userRouter로 이동

app.get('/', (req, res) => {
  res.send('Hello World. 안녕하세요')
})

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


// export default server
