import { Type } from "@sinclair/typebox";
import { FirRouteOptions, FirWebsocketHandler, FirWebsocketInput } from "../util/routewrap.js";
import { WebSocket } from "@fastify/websocket";
import { FastifyRequest } from "fastify";

const method = "GET";
const url = "/api/ws/room";

const payloadT = Type.Any();

type Room = {
	name: string;
	sockets: WebSocket[];
}

let rooms: Room[] = [];

const getRoomName = (req: FastifyRequest) => {
	return (req.query as any).room;
}

const websocket = {
	onOpen({socket, req}) {
		const roomName = getRoomName(req);
		let room = rooms.find(r => r.name === roomName);
		if (!room) {
			console.log("creating room", roomName);
			room = {
				name: roomName,
				sockets: [],
			};
			rooms.push(room);
		}
		if (!room.sockets.includes(socket)) {
			console.log("adding socket to room", roomName);
			room.sockets.push(socket);
		}
		console.log('rooms', rooms);
	},
	onClose({socket, req}) {
		const roomName = getRoomName(req);
		const room = rooms.find(r => r.name === roomName);
		if (room) {
			room.sockets = room.sockets.filter(sock => sock !== socket);
			if (room.sockets.length === 0) {
				rooms = rooms.filter(r => r !== room);
			}
		}
		console.log('rooms', rooms);
	},
	onMessage({socket, payload, req}) {
		const roomName = getRoomName(req);
		let room = rooms.find(r => r.name === roomName);
		if (!room) {
			console.log("creating room", roomName);
			room = {
				name: roomName,
				sockets: [],
			};
			rooms.push(room);
		}
		if (!room.sockets.includes(socket)) {
			console.log("adding socket to room", roomName);
			room.sockets.push(socket);
		}
		console.log("replying to everyone else in room", roomName);
		room.sockets.forEach(sock => {
			if (sock !== socket) {
				sock.send(JSON.stringify(payload));
			}
		});
		console.log('rooms', rooms);
	},
} as const satisfies FirWebsocketHandler;

export default {
	method,
	url,
	payloadT,
	websocket,
} as const satisfies FirRouteOptions<typeof payloadT>;