import {create_popup} from "../../utils/noticeUtils.js";

class Notice {
	constructor(client) {
		this.client = client;
		this.data = {};

		// users online, invited by, asked friend by, 
		let data_variable = ["online", "invited", "asked"];
		for (let i in data_variable) {
			this.data[data_variable[i]] = [];
		}

		this.connect();

	}

	async connect() {
		let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/chat/notice`;

		this.chatSocket = new WebSocket(url);
		this.chatSocket.onmessage = (event) =>{
			let data = JSON.parse(event.data);
			//console.log("notice: ", data);
			if (data.type == "invite")
				this.receiveInvite(data);
			else if (data.type == "online_users" || data.type == "disconnect")
				this.receiveOnlineUser(data);
		}
	    this.chatSocket.onopen = (event) => {
			this.getOnlineUser();
		}
	}

	async disconnect() {
		if (this.chatSocket == undefined)
			return ;

		this.chatSocket.close();

	}

	async sendInvite(id_inviter, id_inviteds) {
		
		if (this.chatSocket == undefined)
			return;

		this.chatSocket.send(JSON.stringify({
			type: "invite",
			targets: id_inviteds,
		}));

	}

	async receiveInvite(data) {
		
		if (data.content === "notice return") {
			if (data.status == 200) {
				for (let target in data.targets)
					this.data["invited"].push(target);
				return create_popup("Invitation send");
			}
			else if (data.status == 404)
				return create_popup("User not connected");
			else if (data.status == 409)
				return create_popup("Already invited");
		}
		else {
			let sender = await this.client.profiles.getProfile(data.author_id);

			this.inviter.push(data.author_id);
			create_popup("Invitation received by " + sender.username);

			// Géré la reception de l'invitation
		}
	}

	async getOnlineUser() {
		
		if (this.chatSocket == undefined)
			return;

		this.online_users = {};

		this.chatSocket.send(JSON.stringify({
			type: "online_users",
			targets: "all",
		}));

	}

	async receiveOnlineUser(data) {
		if (data.content !== undefined) {

			if (this.online_users.length > 0) {
				// get all disconnect user
				let disconnects = this.online_users.filter(id => !Object.keys(data.content).includes(id));

				// delete invite
				this.data["invited"] = this.data["invited"].filter(id => !disconnects.includes(id));

				//console.log(this.data["invited"]);
			}

			this.data["online"] = Object.keys(data.content);

			if (this.rewrite_usernames !== undefined)
				this.rewrite_usernames();
		}
	}
}

export {Notice}
