import { Injectable, Logger } from '@nestjs/common';
import {
  ConnectedSocket,
  OnGatewayConnection,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
} from '@nestjs/websockets';
import { PlayerService } from './players/player.service';
import { Socket } from 'socket.io';
import { ClientEvent, CreateLobbyEvent, JoinLobbyEvent } from 'interface';

@WebSocketGateway({ cors: true })
@Injectable()
export class AppService implements OnGatewayConnection {
  private readonly logger = new Logger(AppService.name);

  constructor(private readonly playerService: PlayerService) {}
  handleConnection(client: Socket) {
    this.playerService.createPlayer(client.id);
    this.logger.log(client.id);
  }

  @SubscribeMessage(ClientEvent.CREATE_LOBBY)
  handleCreateLobby(
    @ConnectedSocket() client: Socket,
    @MessageBody() event: CreateLobbyEvent,
  ) {
    this.playerService.addUserName(client.id, event.userName);
    this.logger.log('Se ha creado un lobby');
  }

  @SubscribeMessage(ClientEvent.JOIN_LOBBY)
  handleJoinLobby(
    @ConnectedSocket() client: Socket,
    @MessageBody() event: JoinLobbyEvent,
  ) {
    this.playerService.addUserName(client.id, event.userName);
    this.logger.log('Te has unido a un lobby');
  }
}
