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('onUserChangeStatus', 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('onUserChangeStatus', userDesconectado);
    }
    client.leave('chat_general');
  }

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

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

  @SubscribeMessage('createPartida')
  handleCreatePartida(client: Socket) {
    const userId = client.handshake.auth.userId;
    const partida = this.salaChatService.creaPartida(userId);
    client.broadcast.to('chat_general').emit('onCreatePartida', partida);
    return partida;
  }

  @SubscribeMessage('cancelPartida')
  handleCancelPartida(client: Socket, uuidPartida: string) {
    const userId = client.handshake.auth.userId;
    const uuidPartidaEliminado = this.salaChatService.eliminarPartida(
      userId,
      uuidPartida,
    );
    if (uuidPartidaEliminado)
      client.broadcast
        .to('chat_general')
        .emit('onCancelPartida', uuidPartidaEliminado);
    return uuidPartidaEliminado;
  }

  @SubscribeMessage('joinPartida')
  handleJoinPartida(client: Socket, uuidPartida: string) {
    const userId = client.handshake.auth.userId;
    const partida = this.salaChatService.unirsePartida(userId, uuidPartida);
    client.broadcast.to('chat_general').emit('onJoinPartida', partida);
    return partida;
  }
}