import { autoResize, creerBlocDOM } from './utils.js'
import { renderBlocStyle, renderListe } from './functionsBloc.js'

export function initSocketBloc() {
    const params = new URLSearchParams(window.location.search);
    const pageId = parseInt(params.get("id"));
    if (!pageId) return;

    const socketBloc = new WebSocket("ws://" + window.location.host + `/Projet/ws/bloc?pageId=${pageId}`);
	window.socketBloc = socketBloc
	
	socketBloc.onopen = () => {
		const login = document.getElementById("user-login").textContent;
	    socketBloc.send(JSON.stringify({
	        action: "nouvelleConnexion",
	        utilisateur: login
	    }));
	};
	
    socketBloc.onmessage = event => {
        const data = JSON.parse(event.data);
		
        if (data.action === "update") {
            const blocElement = document.querySelector(`.editor[data-id='${data.blocId}']`);
            if (blocElement) {
                blocElement.innerHTML = data.content;
                blocElement.setAttribute('data-metadata', data.metadata);
				autoResize(blocElement);
            }
        } else if (data.action === "users") {
			const dropdown = document.getElementById("connected-users-dropdown");
			if (dropdown === null) return;
			dropdown.innerHTML = "";
	        data.users.forEach(user => {
	            const item = document.createElement("div");
	            item.className = "navbar-item";
	            item.textContent = user;
	            dropdown.appendChild(item);
	        });
	    } else if (data.action === "newBloc") {	
			creerBlocDOM({
				blocId: data.blocId,
				content: data.content,
				type: data.type,
				metadata: data.metadata || "{}",
				ordre: data.ordre
			});	
		} else if (data.action === "actualiserMiseEnPageBloc") {
			const blocElement = document.querySelector(`.editor[data-id='${data.blocId}']`);
			if (blocElement) {
				blocElement.dataset.type = data.type;
				blocElement.innerHTML = data.content;
				blocElement.dataset.metadata = JSON.stringify(data.metadata || {});
				blocElement.className = data.classBloc;
				renderBloc(blocElement, blocElement.dataset.metadata);
			}				
		}
    };

    document.querySelectorAll('.editor').forEach(bloc => {
        bloc.addEventListener('input', event => {
            const blocId = event.target.getAttribute('data-id');
            const content = event.target.innerHTML;
            const type = event.target.getAttribute('data-type');
            const metadata = event.target.getAttribute('data-metadata');

            const modif = {
                action: "update",
                blocId,
                content,
                metadata,
                type
            };

            socketBloc.send(JSON.stringify(modif));
        });
    });
}

export function renderBloc(bloc, metadata) {
	if (!bloc || !bloc.dataset) return;

	const type = bloc.dataset.type || 'TEXTE';

	switch (type) {
		case 'TEXTE':
			bloc.classList.add('is-text');
			break;

		case 'TITRE':
			const level = metadata.level || '1';
			bloc.classList.add('is-title', `is-title-${level}`);
			break;

		case 'LISTE':
			bloc.classList.add('is-list');
			break;

		case 'CODE':
			bloc.classList.add('is-code-block');
			bloc.style.whiteSpace = "pre";
			bloc.dataset.language || 'plaintext';
			break;

		case 'PAGE':
			bloc.classList.add('is-page-link');
			break;

		case 'SEPARATEUR':
			bloc.classList.add('is-separator');
			bloc.contentEditable = "false";
			break;
		case "CITATION":
			const citationType = metadataCitation.type || 'normal';
		    bloc.classList.add('is-quote', `is-quote-${citationType}`);
		    break;

		default:
			bloc.classList.add('is-text');
			break;
	}
	
	autoResize(bloc);
}
