import AbstractView from "./abstracts/AbstractView.js";
import {client} from "../index.js";
import {Message} from "../api/chat/message.js"

export default class extends AbstractView {
    constructor(params) {
        super(params, "Search");
    }

	async wait_get_online_users() {
		return new Promise((resolve) => {
			const checkInterval = setInterval(() => {
				//console.log(client.notice.data["online"].length);
				if (client.notice.data["online"].length > 0) {
					clearInterval(checkInterval);
					resolve();
				}
			}, 100);
		});
	}

	async postInit() {

		let logged = await client.isAuthentificate();
		let profiles = await client.profiles.all();

		//console.log(client.notice.data);
		if (client.notice.data == undefined || client.notice.data["online"] == undefined)
			return console.log("Error");

		//await client.notice.getOnlineUser();
		await this.wait_get_online_users();
		client.notice.rewrite_usernames = this.rewrite_usernames;

		let search = document.getElementById("input_user");
		search.oninput = () => this.display_users(logged, profiles);

		let chat_input = document.getElementById("input_chat");
		//chat_input.addEventListener("keydown", this.display_chat_manager)

		this.last_add_chat = undefined;

		this.display_users(logged, profiles);
		this.display_chat(logged, profiles);

	}

	async display_users(logged, profiles) {

		let search = document.getElementById("input_user").value.toLowerCase();
		
		let list_users = document.getElementById('list_users');
		list_users.innerHTML = "";

		profiles.filter(user => user.username.toLowerCase().startsWith(search) == true).forEach((user) => {

			if (user.id == null) {
				console.log("list User one with id null;");
				return;
			}

			var new_user = document.createElement("li");

			// username
			let username = document.createElement("a");
			username.setAttribute('data-link', '');
			username.id = `username${user.id}`
			username.href = `/profiles/${user.username}`;
			username.style.color = client.notice.data["online"].includes(user.id.toString()) ? "green" : "red";
			username.appendChild(document.createTextNode(user.username));
			new_user.appendChild(username);

			// space
			new_user.appendChild(document.createTextNode(" "));

			// button chat
			if (logged && client.me.id != user.id) {
				let add_chat = document.createElement("a");
				add_chat.id = "add_chat_off";
				add_chat.onclick = async () => {
					if (client.channels.channel != undefined) {

						// Permet de savoir si c'est le même channel
						// Check to know if it's the same channel
						client.channels.channel.members_id.forEach((member_id) => {
							if (member_id == user.id)
								client.channels.channel = undefined;
						});
						if (client.channels.channel == undefined) {
							add_chat.id = "add_chat_off";
							this.last_add_chat = undefined;
							return await this.hide_chat();
						}

						await client.channels.channel.disconnect();
					}
					client.channels.channel = await client.channels.createChannel([client.me.id , user.id], () => this.reload_display_messages());
					this.display_chat(logged, profiles);
					if (this.last_add_chat != undefined)
						this.last_add_chat.id = "add_chat_off";
					this.last_add_chat = add_chat;
					add_chat.id = "add_chat_on";
				};
				add_chat.appendChild(document.createTextNode("Chat"));
				new_user.appendChild(add_chat);
				
				new_user.appendChild(document.createTextNode(" "));

			}
			
			// break line
			new_user.appendChild(document.createElement("br"));

			// avatar
			var img = document.createElement("img");
			img.src = user.avatar_url;
			new_user.appendChild(img);


			list_users.appendChild(new_user);
		});
		//console.log(list_users);

	}

	async rewrite_usernames() {
		let search_document = document.getElementById("input_user");

		if (search_document == undefined || search_document == null)
			return

		let search = search_document.value.toLowerCase();
		
		let profiles = await client.profiles.all();

		profiles.filter(user => user.username.toLowerCase().startsWith(search) == true).forEach((user) => {
			let username = document.getElementById(`username${user.id}`);
			if (username !== null)
				username.style.color = client.notice.data["online"].includes(user.id.toString()) ? "green" : "red";
		});

	}

	async display_chat(logged, profiles)
	{
		let reloads = ["members", "messages"];
		reloads.forEach(reload => {
			if (document.getElementById(reload) != undefined)
				document.getElementById(reload).remove();
		});

		if (client.channels.channel === undefined || logged === false)
			return ;

		let chats = document.getElementById("chats");

		if (document.getElementById("chat") == null) {
			let chat = document.createElement("div");
			chat.id = "chat";
			chats.appendChild(chat);
		}

		// nom des membres du channel
		let members = await this.display_members(chat, profiles);

		// L'affiche des messages
		let messages = await this.display_messages(chat);

		// Input pour rentrer un message
		let chat_input = document.getElementById("input_chat") || document.createElement("input");
		chat_input.id="input_chat";
		chat_input.type="text";
		chat_input.name="message";
		chat_input.placeholder="message bozo";
		chat_input.maxLength=255;
		chat.appendChild(chat_input);
		
		chat_input.onkeydown = async () => {
			if (event.keyCode == 13 && client.channels.channel != undefined) {
				//let chat_input = document.getElementById("input_chat");
				let chat_text = chat_input.value;

					let receivers_id = [];
					client.channels.channel.members_id.forEach((member_id) => {
						if (member_id != client.me.id)
							receivers_id.push(profiles.filter(user => user.id == member_id)[0].id);
					});
					await client.channels.channel.sendMessageChannel(chat_text, receivers_id);
				// Reset
				chat_input.value = "";
			}
		};
		chat_input.focus();


		// Scroll to the bottom of messages
		messages.scrollTop = messages.scrollHeight;

		this.display_invite(chat);

	}

	async display_messages(chat) {

		let messages = document.createElement("div");

		messages.id = "messages";
		chat.appendChild(messages);

		// les messages, réecriture seulement du dernier 
		client.channels.channel.messages.forEach((message) => {
			let text = document.createElement("p");
			let date = new Date(message.time);
			text.title = date.toLocaleString("fr-FR");
			text.appendChild(document.createTextNode(message.content));
			text.id = message.author_id === client.me.id ?  "you" : "other";

			messages.appendChild(text);
		});

		return messages
	}

	async reload_display_messages() {
		let messages = document.getElementById("messages");

		let i = 0;
		client.channels.channel.messages.forEach((message) => {
			if (messages.children[i] == null || message.content != messages.children[i].innerText) {
				let text = document.createElement("p");
				let date = new Date(message.time);
				text.title = date.toLocaleString("fr-FR");
				text.appendChild(document.createTextNode(message.content));
				text.id = message.author_id === client.me.id ?  "you" : "other";

				messages.appendChild(text);
			}
			i++;
		});

		messages.scrollTop = messages.scrollHeight;
	}

	async display_members(chat, profiles) {
		let members = document.createElement("h2");
		members.id = "members";
		let usernames = "";
		client.channels.channel.members_id.forEach((member_id) => {
			if (member_id != client.me.id) {
				if (usernames.length > 0)
					usernames += ", ";
				usernames += (profiles.filter(user => user.id == member_id)[0].username);
			}
		});
		members.appendChild(document.createTextNode(usernames));
		chat.appendChild(members);

		return members
	}

	async display_invite(chat, profiles) {

		// Button to send invite to play
		let invite = document.getElementById("invite") || document.createElement("button");
		invite.id = "invite";
		invite.innerText = "invite";
		invite.onclick = async () => {
			await client.notice.sendInvite(client.me.id, 
				client.channels.channel.members_id.filter(id => id !== client.me.id));
		};
		chat.appendChild(invite);

	}

	async hide_chat() {

		let closes = ["chat", "invite"]
		closes.forEach(close => {
			if (document.getElementById(close))
				document.getElementById(close).remove();
				
		});
	}

	async leavePage() {
		if (client.channels.channel != undefined)
			client.channels.channel.disconnect();
		client.channels.channel = undefined;

	}

    async getHtml() {
        return `
			<link rel="stylesheet" href="/static/css/search.css">

			<div id="chats">
				<div id="users">
					<input id="input_user" type="text" name="message" placeholder="userbozo"/>
					<ul id="list_users">
					</ul>
				</div>
			</div>
        `;
    }
}
