{"size": 1403, "ext": "js", "max_stars_repo_path": "modules/ioEvents.js", "max_stars_repo_name": "Falicer/didactic-lamp", "max_stars_repo_stars_event_min_datetime": "2021-06-16T16:19:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T16:19:52.000Z", "max_issues_repo_path": "modules/ioEvents.js", "max_issues_repo_name": "Falicer/petscout-pt", "max_issues_repo_issues_event_min_datetime": "2021-06-02T08:13:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T14:08:54.000Z", "max_forks_repo_path": "modules/ioEvents.js", "max_forks_repo_name": "Falicer/didactic-lamp", "max_forks_repo_forks_event_min_datetime": "2021-06-03T13:35:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T13:35:26.000Z"}
{"max_stars_count": 1, "max_issues_count": 30, "max_forks_count": 1, "avg_line_length": 22.2698412698, "max_line_length": 75, "alphanum_fraction": 0.5972915182}
const formatMessage = require('./messages');
const {
  userJoin,
  getCurrentUser,
  userLeave,
  getRoomUsers
} = require('./users');
const botName = 'Petscout Alice';


exports.ioEvents = (socket, io) => {

  socket.on('joinRoom', ({
    username,
    room
  }) => {
    const user = userJoin(socket.id, username, room);

    socket.join(user.room);

    // Welcome current user
    socket.emit('message', formatMessage(botName, 'Welcome to ChatCord!'));

    // Broadcast when a user connects
    socket.broadcast
      .to(user.room)
      .emit(
        'message',
        formatMessage(botName, `${user.username} has joined the chat`)
      );

    // Send users and room info
    io.to(user.room).emit('roomUsers', {
      room: user.room,
      users: getRoomUsers(user.room)
    });
  });

  // Listen for chatMessage
  socket.on('chatMessage', msg => {
    const user = getCurrentUser(socket.id);

    io.to(user.room).emit('message', formatMessage(user.username, msg));
  });

  // Runs when client disconnects
  socket.on('disconnect', () => {
    const user = userLeave(socket.id);

    if (user) {
      io.to(user.room).emit(
        'message',
        formatMessage(botName, `${user.username} has left the chat`)
      );

      // Send users and room info
      io.to(user.room).emit('roomUsers', {
        room: user.room,
        users: getRoomUsers(user.room)
      });
    }
  });
}