export class Clients {
  constructor() {
    this.sockets = {};
  }

  addSocket(userId, socket, data) {
    this.sockets[userId] = { data: data || {}, socket, userId };
  }

  updateData(userId, data) {
    this.sockets[userId].data = data;
  }

  sendTo(userId, event, data) {
    const socket = this.sockets[userId].socket;
    if (socket) {
      socket.emit(event, data);
    }
  }

  broadcast(event, data) {
    if (!Object.keys(this.sockets).length) return;
    Object.keys(this.sockets).forEach((userId) =>
      this.sendTo(userId, event, data)
    );
  }

  listData() {
    return Object.values(this.sockets).map((item) => {
      return { userId: item.userId, data: item.data };
    });
  }

  listUsers() {
    return Object.keys(this.sockets);
  }

  removeSocket(userId) {
    delete this.sockets[userId];
  }
}
