import { WebSocketGateway, SubscribeMessage, WebSocketServer, MessageBody, ConnectedSocket, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { UsersService } from 'src/users/users.service';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { ChatService } from './chat.service';

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

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

  @WebSocketServer()
  server;


	// how to guard the handleConnection ?
	// https://github.com/nestjs/nest/issues/882
	async handleConnection(client) {
		console.log('- Client connected :', client.id, client.handshake.query.username);
		client.username = client.handshake.query.username;
	}
	async handleDisconnect(client) {
		console.log('- Client disconnected :', client.id, client.username);
	}

	@SubscribeMessage('join')
	async joinRoom(@ConnectedSocket() socket, @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);

		console.log('- out joinRoom gateway');
	}

	@SubscribeMessage('change')
	async changeRoom(@ConnectedSocket() socket, @MessageBody() room_name: string): Promise<void>
	{
		console.log('- in changeRoom gateway');
		socket.leave(socket.room);
		socket.join(room_name);
		socket.room = room_name;

		console.log('- out changeRoom gateway');
	}

	@SubscribeMessage('message')
	async handleMessage(@ConnectedSocket() socket, @MessageBody() message: string): Promise<void>
	{
		console.log('- in handleMessage gateway');
		//let room_name = await this.chatService.getCurrentRoom(socket.username);
		socket.to(socket.room).emit('message', socket.username, message);
		let room_name = await this.chatService.getCurrentRoomName(socket.username);
		await this.chatService.addMessageToRoom(room_name, socket.username, message);

		console.log('- out handleMessage gateway');
	}
}

