/*
	************************************************
	folderHorizon service.js
	* Editor & Status service
	* See vars in global_service.tpl
	* Not loaded in release
	************************************************
*/

/***************************************************
	Editor service
*/
const article = document.getElementById('article'),
	placeholder = '<div class="editor-placeholder"><i>double-click to write text</i></div>',
	editorWrapper = document.getElementById('editorWrapper'),
	editor = Jodit.make('#editor', {
		toolbarButtonSize: 'small',
		placeholder: 'Write or paste here...',
		buttons: 'paragraph,|,bold,italic,underline,|,align,|,indent,outdent,|,eraser,|,hr,|,ul,ol,|,link,|,copy,cut,paste,|,selectall,|,undo,redo'
	}),
	editorContent = document.getElementsByClassName('jodit-wysiwyg')[0];

// Double-click to open editor
article.addEventListener('dblclick', function () {
	this.classList.add('hide');
	editorWrapper.classList.remove('hide');
});

// Close button
document.getElementById('editorClose').addEventListener('click', function () {
	editorWrapper.classList.add('hide');
	// editor.value | editor.getEditorValue()
	article.innerHTML = editorHasContent() ? editor.getEditorValue() : placeholder;
	article.removeAttribute('class');
});

// Save button
document.querySelector('#editorSave').addEventListener('click', () => {
	editorWrapper.classList.add('hide');
	// editor.value | editor.getEditorValue()
	editorService(editorHasContent() ? editor.getEditorValue() : '');
});

// Check if editor has text content
function editorHasContent() {
	return editorContent.textContent.trim() !== '';
}

// XMLHttpRequest
function editorService(html) {
	const xhr = new XMLHttpRequest();
	xhr.open('POST', serviceUrl + '/editor', true); // ...
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4) {
			if (xhr.status === 200) {
				if (xhr.responseText) {
					const res = JSON.parse(xhr.responseText);
					article.innerHTML = (res.text !== '') ? res.text : placeholder;
					editor.value = res.text;
					article.removeAttribute('class');
				}
			}
		}
	};
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	xhr.send(JSON.stringify({ text: html, file: editorTextFile })); // ...
}

editorService('[LoadFile]');

/***************************************************
	Status service
*/
const idAlertChanges = 'alertChanges',
	idModalLoader = 'modalLoader',
	updating = 'updating';

let sendUpdate = false; // Reload page!

// XMLHttpRequest interval
setInterval(function () {
	const xhr = new XMLHttpRequest();
	xhr.timeout = 1500;
	xhr.open('POST', serviceUrl + '/status', true); // ...
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4) {
			if (xhr.status === 200) {
				if (xhr.responseText) {
					const res = JSON.parse(xhr.responseText);
					if (idNull(idAlertChanges) && res.status === 'changed') {
						alertChanges();
					} else if (idNull(idModalLoader) && res.status === 'building') {
						modalLoader(updating);
					} else if (res.status === 'reload') {
						// This file exists, just reload page
						location.reload();
					} else if (res.status === 'home') {
						// This file has been deleted OR archive released
						// statusBackRef is empty string on root/index
						window.location.replace(statusBackRef + 'index.html');
					}
				}
			} else if (idNull(idModalLoader)) {
				modalLoader('folderHorizon service is not active');
			}
		}
	};
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	xhr.send(JSON.stringify({ status: statusIndexFile, update: sendUpdate })); // ...
}, 3000);

// Check element not exists
function idNull(id) {
	return document.getElementById(id) === null;
}

// Alert on archive changes
function alertChanges() {
	if (!idNull(idModalLoader)) return;
	const bar = document.createElement('div'),
		btn = document.createElement('span');
	// wrapper bar
	bar.id = idAlertChanges;
	bar.style.position = 'fixed';
	bar.style.zIndex = 8;
	bar.style.left = 0;
	bar.style.bottom = '1rem';
	bar.style.width = '100%';
	bar.style.textAlign = 'center';
	// button
	btn.className = 'pointer-noselect';
	btn.style.backgroundColor = '#000000';
	btn.style.color = '#CCCCCC';
	btn.style.fontSize = '1rem';
	btn.style.fontWeight = 700;
	btn.style.padding = '0.5rem 1rem';
	btn.style.opacity = 0.8;
	btn.textContent = 'UPDATE CHANGES';
	btn.addEventListener('click', function () {
		sendUpdate = true;
		modalLoader(updating);
	});
	bar.appendChild(btn);
	document.body.appendChild(bar);
}

// Modal loader on updating changes
function modalLoader(msg) {
	if (!idNull(idAlertChanges)) document.getElementById(idAlertChanges).remove();
	const el = document.createElement('div');
	el.id = idModalLoader;
	el.style.position = 'fixed';
	el.style.zIndex = 9;
	el.style.top = 0;
	el.style.left = 0;
	el.style.opacity = 0.5;
	el.style.width = '100%';
	el.style.height = '100vh';
	el.style.backgroundColor = '#FFFFFF';
	el.style.backgroundImage = "url('" + statusLoaderImg + "')"; // ...
	el.style.backgroundRepeat = 'no-repeat';
	el.style.backgroundPosition = 'center';
	el.style.backgroundSize = '4rem';
	el.style.paddingTop = '54vh';
	el.style.color = '#000000';
	el.style.fontSize = '1rem';
	el.style.fontWeight = 700;
	el.style.textAlign = 'center';
	el.textContent = msg;
	document.body.prepend(el);
}
