import {
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { SalaChatService } from './sala-chat.service';
import { Server, Socket } from 'socket.io';
import { Resp } from 'src/interfaces/resp';

@WebSocketGateway({ namespace: 'salachat' })
export class SalaChatGateway
  implements OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer()
  server: Server;
  constructor(private readonly salaChatService: SalaChatService) {}

  handleConnection(client: Socket) {
    const userId = client.handshake.auth.userId;
    const userConectado = this.salaChatService.conectaUsuarioUUID(userId);
    if (userConectado) {
      client.join('chat_general');
      client.emit('onConnectRoom', {
        usuarios: this.salaChatService.listaUsuariosSinPartidas,
        partidas: this.salaChatService.partidasAbiertas,
      });
      client.broadcast
        .to('chat_general')
        .emit('onUserConnectRoom', userConectado);
    } else {
      client.disconnect();
    }
  }

  handleDisconnect(client: Socket) {
    const userId = client.handshake.auth.userId;
    const userDesconectado = this.salaChatService.desconectaUsuarioUUID(userId);
    if (userDesconectado) {
      client.broadcast
        .to('chat_general')
        .emit('onUserDisconnectRoom', userDesconectado);
    }
    client.leave('chat_general');
  }

  @SubscribeMessage('chatMsg')
  handleMsg(client: Socket, msg: string) {
    const userId = client.handshake.auth.userId;
    const user = this.salaChatService.getUsuarioUUID(userId);
    if (user) {    
      client.broadcast.to('chat_general').emit('chatMsg',{ uuid: userId, msg });
      return { uuid: userId, msg };
    } else {
      client.disconnect();
    }
  }

  sendBroadcastMsg(msg: string) {
    this.server.to('chat_general').emit('broadcastMsg', msg);
  }

  @SubscribeMessage('creaPartida')
  handleCreaPartida(client: Socket) {
    const userId = client.handshake.auth.userId;
    const partida = this.salaChatService.creaPartida(userId);
    this.server.to('chat_general').emit('onCrearPartida', partida);
  }
}
