import { msgs, user, layout, socket, current_room_name } from './Store_chat';
import type { Room } from './Interface_chat';


export async function get_room_messages()
{
	console.log("in get_room_messages");
	const response = await fetch('/api/v2/chat/messages');
	const data = await response.json();
	const messages = data.messages;

	if (messages === null)
		return;

	messages.forEach(function(item) {
		if (item.name === user.username) {
			item.name = "me";
		}
	});

	msgs.set(messages);
}

export async function create_room(room: Room)
{
	console.log("in create_room");

	// send the new room
	const response = await fetch('/api/v2/chat/create', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(room),
	});

	// get response status and message
	let response_status = response.status;
	let data = await response.json();
	let response_message = "";

	return {
		status: response_status,
		message: data.message,
		room: data.room,
	};
}

export async function join_room(room: Room)
{
	console.log("in join_room");

	const response = await fetch('/api/v2/chat/join', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(room),
	});
	let data = await response.json();

	return data.room;
}

export async function change_room(room: Room)
{
	console.log("in change_room");

	console.log("room:", room);
	const response = await fetch('/api/v2/chat/change', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(room),
	});
	let data = await response.json();

	await get_room_messages();

	let room_name = data.room.name;
	if (room.type === 'direct')
	{
		room_name === room.users[0];
		if (room_name === user.username)
			room_name === room.users[1];
	}
	current_room_name.set(room_name);
	layout.set("room");
}

export async function get_my_rooms()
{
	console.log("in get_my_rooms");

	const response = await fetch('/api/v2/chat/myrooms');
	const data = await response.json();
	console.log("data.rooms:", data.rooms);

	return data.rooms;
}

export async function get_all_rooms()
{
	console.log("in get_all_rooms");

	const response = await fetch('/api/v2/chat/allrooms');
	const data = await response.json();

	return data.rooms;
}

export async function get_room_users()
{
	console.log("in get_room_users");

	const response = await fetch('/api/v2/chat/roomusers');
	const data = await response.json();

	return data.users;
}

export async function user_leave_room()
{
	console.log("in leave_room");

	const response = await fetch('/api/v2/chat/removeuser', {
		method: 'DELETE',
	});
}


