import {
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
} from '@nestjs/websockets';
import { BatallaService } from './batalla.service';
import { Socket } from 'socket.io';
import Barco from 'src/battleship/barco';

@WebSocketGateway({ namespace: 'batalla' })
export class BatallaGateway
  implements OnGatewayConnection, OnGatewayDisconnect
{
  constructor(private readonly batallaService: BatallaService) {}

  handleConnection(client: Socket) {
    const { userId, gameId } = client.handshake.auth;
    if (this.batallaService.existePartidaUsuario(gameId, userId)) {
      client.emit(
        'OnChangeState',
        this.batallaService.getSnapshotJugador(gameId, userId),
      );
    } else {
      client.disconnect();
    }
  }

  handleDisconnect(client: Socket) {}

  @SubscribeMessage('setFlota')
  handleMsg(client: Socket, barcos: Barco[]) {
    const { userId, gameId } = client.handshake.auth;
    const snapshotJugador = this.batallaService.getSnapshotJugador(gameId,userId);
    snapshotJugador.prepararFlota(barcos);
    return snapshotJugador;
  }
}
