import { WebSocketGateway, SubscribeMessage, WebSocketServer, MessageBody, ConnectedSocket, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { UsersService } from 'src/users/users.service';
import { ChatService } from './chat.service';
import { socketDto } from './dto/socket.dto';

@WebSocketGateway(5000, {
	path: '/chat',
})

export class ChatGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
	constructor
	(
		private usersService: UsersService,
		private chatService: ChatService,
	) {}

	sockets = new Map<string, socketDto>();

  @WebSocketServer()
  server;

	async handleConnection(socket: socketDto) {
		console.log('- socket connected :', socket.id, socket.handshake.query.username);
		socket.username = socket.handshake.query.username.toString();
		this.sockets.set(socket.username, socket);
	}
	async handleDisconnect(socket: socketDto) {
		this.sockets.delete(socket.username);
	}

	@SubscribeMessage('join')
	async joinRoom(@ConnectedSocket() socket: socketDto, @MessageBody() room_name: string): Promise<void>
	{
		console.log('- in joinRoom gateway');
		socket.leave(socket.room);
		socket.join(room_name);
		socket.room = room_name;
		let message = `${socket.username} has join the room`;
		await socket.to(socket.room).emit('message', "SERVER", message);
		await this.chatService.addMessageToRoom(room_name, "SERVER", message);
	}

	@SubscribeMessage('change')
	async changeRoom(@ConnectedSocket() socket: socketDto, @MessageBody() room_name: string): Promise<void>
	{
		console.log('- in changeRoom gateway');
		await this.chatService.socketChangeRoom(socket, room_name);
	}

	@SubscribeMessage('message')
	async handleMessage(@ConnectedSocket() socket: socketDto, @MessageBody() message: string): Promise<void>
	{
		console.log('- in handleMessage gateway');
		await this.chatService.socketIncommingMessage(socket, message);
	}
}

