/* scripts */

/**
 * Chiamata di recupero dati da feed RSS
 *
 * @param {String} url
 */
function getFeedRSS(url) {
	const xhr = new XMLHttpRequest();
	xhr.open("GET", url, true);
	xhr.responseType = "text";
	xhr.onload = function () {
		if (xhr.status === 200) {
			parseRSS(xhr.responseText);
		}
	};
	xhr.send();
}

function parseRSS(feedRSS) {
	const parser = new DOMParser();
	const fixedFeedRss = feedRSS.replace("&ndash;", "");
	const xmlDoc = parser.parseFromString(fixedFeedRss, "text/xml");
	const items = xmlDoc.querySelectorAll("item");
	if (items.length) {
		renderItems(items);
	}
}

function renderItems(items) {
	const showcase = document.querySelector("#showcase");
	if (showcase) {
		const maxItems = 4;
		for (let i = 0; i < items.length && i < maxItems; i++) {
			showcase.appendChild(renderItem(items[i]));
		}
	} else {
		console.warn("Showcase missing");
	}
}

/**
 * Formatta la data nel formato richiesto
 *
 * @param {Date} date
 */
function formatDate(date) {
	const day = date.getDate();
	const months = [
		"Gennaio",
		"Febbraio",
		"Marzo",
		"Aprile",
		"Maggio",
		"Giugno",
		"Luglio",
		"Agosto",
		"Settembre",
		"Ottobre",
		"Novembre",
		"Dicembre",
	];
	const month = months[date.getMonth()];
	const year = date.getFullYear();
	return `${day} ${month} ${year}`;
}

/**
 * Renderizzo singolo elemento
 *
 * @param {HTMLElement} item
 * @return {HTMLElement}
 */
function renderItem(item) {
	const classname = "rssfeed-article";
	const itemNode = document.createElement("div");
	itemNode.className = classname + " col-12 col-xl-6";

	/* create columns */
	const leftColumn = document.createElement("div");
	leftColumn.className = classname + "__left-content";
	itemNode.appendChild(leftColumn);

	const rightColumn = document.createElement("div");
	rightColumn.className = classname + "__right-content";
	itemNode.appendChild(rightColumn);

	/* get fields */
	const title = item.querySelector("title");
	const category = item.querySelector("category");
	const description = item.querySelector("description");
	const link = item.querySelector("link");
	const pubDate = item.querySelector("pubDate");

	if (title && link) {
		/* render title with link */
		const titleElement = document.createElement("a");
		titleElement.className = classname + "__title";
		const text = title.textContent;
		if (text.length > 40) {
			titleElement.innerText = text.slice(0, 40) + "\u2026";
		} else {
			titleElement.innerText = text;
		}
		titleElement.href = link.textContent;
		titleElement.title = title.textContent;
		titleElement.target = "_blank";
		rightColumn.appendChild(titleElement);
		rightColumn.appendChild(document.createElement("br"));

		if (category) {
			const categoryElement = document.createElement("div");
			categoryElement.className = classname + "__category";
			categoryElement.innerText = category.textContent;
			rightColumn.appendChild(categoryElement);
		}

		if (pubDate) {
			const pubDateElement = document.createElement("div");
			pubDateElement.className = classname + "__publish-date";
			pubDateElement.innerText = formatDate(new Date(pubDate.textContent));
			rightColumn.appendChild(pubDateElement);
		}

		const imageElement = document.createElement("div");
		imageElement.className = classname + "__image";

		if (description) {
			/* create temporary element to retrieve image from description field */
			const temp = document.createElement("div");
			temp.innerHTML = description.textContent;
			const img = temp.querySelector("img");
			if (img) {
				imageElement.appendChild(img);
			}
			delete temp;
		}
		leftColumn.insertBefore(imageElement, null);
	}
	return itemNode;
}

/* impaginazione */
document.addEventListener("DOMContentLoaded", function (event) {
	const url = rcmail.gettext('login_info.focus_url');
	const refreshButton = document.querySelector("#messagelist-header .button.icon.refresh");

	if (rcmail.env.task == 'login' || rcmail.env.task == 'logout') {
		getFeedRSS(url + "feed/");
	}

	if (refreshButton) {
		const menuButtonsWrapper = document.getElementById("menu-buttons-wrapper");

		if(window.matchMedia("(max-width: 768px)").matches) {
			setTimeout(() => {
				menuButtonsWrapper.append(refreshButton);
			}, 0);
		}

		window.matchMedia("(max-width: 768px)").onchange = (e) => {
			if (e.matches) {
				setTimeout(() => {
					menuButtonsWrapper.append(refreshButton);
				}, 0);
			}
		};	
	}
});
