import { addDeleteBloc, addBlocEvent } from './bloc.js'
import { activerCollagePropre } from './collagePropre.js'


export function autoResize(bloc) {
    bloc.style.height = 'auto';
    bloc.style.height = bloc.scrollHeight + 'px';
}

export function placeCursorAtEnd(element) {
    const range = document.createRange();
    const selection = window.getSelection();

    range.selectNodeContents(element);
    range.collapse(false);

    selection.removeAllRanges();
    selection.addRange(range);

    element.scrollIntoView({ behavior: "smooth", block: "end" });
}

export function creerBlocDOM({ blocId, content = "", type = "TEXTE", metadata = "{}", ordre = null }) {
	const container = document.createElement('div');
	container.classList.add('field', 'is-grouped', 'is-align-items-flex-start', 'bloc-container');

	const control = document.createElement('div');
	control.classList.add('control', 'is-expanded');

	const newBloc = document.createElement('div');
	newBloc.classList.add('is-primary', 'editor');
	newBloc.setAttribute('contenteditable', 'true');
	newBloc.setAttribute('data-type', type);
	newBloc.setAttribute('data-id', blocId);
	newBloc.setAttribute('data-metadata', metadata);
	newBloc.innerHTML = content;

	control.appendChild(newBloc);
	container.appendChild(control);

	const delBtnWrapper = document.createElement('div');
	delBtnWrapper.classList.add('control');

	const delBtn = document.createElement('button');
	delBtn.classList.add('delete', 'is-danger', 'delete-bloc-btn');
	delBtn.setAttribute('data-id', blocId);

	delBtnWrapper.appendChild(delBtn);
	container.appendChild(delBtnWrapper);

	// Insertion à la bonne position
	const parent = document.getElementById('md');
	const blocs = parent.querySelectorAll('.bloc-container');
	if (ordre === null || ordre >= blocs.length) {
		parent.appendChild(container);
	} else {
		parent.insertBefore(container, blocs[ordre]);
	}

	// Activation comportements
	addDeleteBloc(delBtn);
	addBlocEvent(newBloc);
	activerCollagePropre(newBloc);
	autoResize(newBloc);

	return newBloc;
}
