let NewsEditor = (function () {
	let module = {};

	let __ButtonAddNews = document.querySelector(".news-add");
	if (__ButtonAddNews) {
		__ButtonAddNews.onclick = addNewsModal;
	}

	/**
	 * Собрать все данные и отправить на БД
	 *
	 * @param {HTMLInputElement} caption
	 * @param {HTMLInputElement} link
	 * @param {HTMLDivElement} content
	 * @param {HTMLDivElement} images
	 * @param {HTMLInputElement} file
	 */
	function create(caption, link, content, images, file) {
		if (!caption || !link || !content || !images) {
			Messenger.Show("Некоторые элементы не были найдены, невозможно создать новость!");
			return;
		}

		if (caption.value.length == 0) {
			Messenger.Show("Необходимо заполнить заголовок!");
			return;
		}

		if (link.value.length == 0) {
			link.value = Main.GenerateHash256();
		}

		let preview = {
			Valid: true,
			String: "",
		};
		let contentHtml = "";

		for (const c of content.blocks) {
			switch (c.type) {
				case "paragraph":
					contentHtml += "<p>" + c.data.text + "</p>";
					preview.String += c.data.text;
					break;
				case "header":
					contentHtml += "<h" + c.data.level + ">" + c.data.text + "/h" + c.data.level + ">";
					preview.String += c.data.text;
					break;
				case "list":
					if (c.data.style === "ordered") {
						contentHtml += "<ol>";

						for (const li of c.data.items) {
							contentHtml += "<li>" + li + "</li>";
							preview.String += li;
						}

						contentHtml += "</ol>";
					} else {
						contentHtml += "<ul>";

						for (const li of c.data.items) {
							contentHtml += "<li>" + li + "</li>";
							preview.String += li;
						}

						contentHtml += "</ul>";
					}
					break;
				case "delimiter":
					contentHtml += "<hr>";
					break;
				case "table":
					contentHtml += "<table>";

					for (const row of c.data.content) {
						contentHtml += "<tr>";

						for (const col of row) {
							contentHtml += "<td>" + col + "</td>";
							preview.String += col;
						}

						contentHtml += "</tr>";
					}

					contentHtml += "</table>";
					break;
			}
		}

		if (preview.String.length > 260) {
			preview.String = preview.String.slice(0, 260);
		}

		var date = new Date();

		let m = ("00" + (date.getMonth() + 1)).slice(-2);
		let d = ("00" + date.getDate()).slice(-2);

		var imageFullpath = "image/news/" + date.getUTCFullYear().toString() + "-" + m + "-" + d + "/";
		var thumbFullpath = "thumb/news/" + date.getUTCFullYear().toString() + "-" + m + "-" + m + "/";

		let selectedImage = {
			Valid: false,
			String: "",
		};

		let selectedInput = images.querySelector("input:checked");
		if (selectedInput) {
			let img = selectedInput.closest(".image").querySelector("img");
			if (img) {
				selectedImage.String = thumbFullpath + img.alt.toLowerCase();
				selectedImage.Valid = true;
			}
		}

		let data = new FormData();

		if (file.files.length > 0) {
			contentHtml += '<div class="news-images">';
			for (const f of file.files) {
				let filename = f.name.toLowerCase();

				contentHtml += '<a href="/' + imageFullpath + filename + '" data-fslightbox="' + link.value + '"><img src="/' + thumbFullpath + filename + '" alt="' + filename + '"></a>';

				data.append("Files", f, filename);
			}
			contentHtml += "</div>";
		}

		data.set("Caption", caption.value);
		data.set("Link", link.value);
		data.set("Content", contentHtml);
		data.set("Source", JSON.stringify(content));
		data.set("PreviewValid", preview.Valid);
		data.set("PreviewString", preview.String);
		data.set("ImageValid", selectedImage.Valid);
		data.set("ImageString", selectedImage.String);
		data.set("ImagePath", imageFullpath);
		data.set("ThumbPath", thumbFullpath);

		let closeModal = this.closest(".modal").querySelector(".close");

		XHR.POST(
			function (result) {
				if (result && "Error" in result) {
					if (result.Error === null) {
						Messenger.Show("Новость успешно добавлена");
						closeModal.click();
					} else {
						Messenger.Show("Возникла ошибка добавления новости." + result.Error);
					}
				}
			},
			"/material-insert/" + MATERIAL_CATEGORY.NEWS,
			data,
			null,
			true,
			true
		);
	}

	/**
	 * Создать модальное окно для добавления новости
	 */
	function addNewsModal() {
		let body = document.createElement("div"),
			inputCaption = document.createElement("input"),
			inputLink = document.createElement("input"),
			contentBlock = document.createElement("div"),
			previewBlock = document.createElement("div"),
			preview = document.createElement("div"),
			label = document.createElement("label"),
			file = document.createElement("input"),
			fileButton = document.createElement("div"),
			buttonSend = document.createElement("button");

		label.append(file, fileButton);
		label.className = "select-file";
		fileButton.className = "button";
		fileButton.textContent = "Выбрать изображениия";

		file.type = "file";
		file.multiple = true;
		file.accept = "image/*";
		file.onchange = changeImages;

		inputCaption.type = "text";
		inputCaption.placeholder = "Заголовок/название (обязательно)";

		inputLink.type = "text";
		inputLink.placeholder = "Ссылка на новость (не обязательно)";

		buttonSend.textContent = "Создать";
		// buttonSend.onclick = create.bind(buttonSend, inputCaption, inputLink, contentBlock, preview, file);

		preview.className = "preview-images";

		contentBlock.id = "editorjs";

		contentBlock.className = "news-content-editor";
		// contentBlock.append(createManipulator());

		body.append(inputCaption, inputLink, contentBlock, previewBlock, label, preview, buttonSend);

		const editor = new EditorJS({
			holderOd: "editorjs",
			tools: {
				header: {
					class: Header,
					inlineToolbar: true,
					config: {
						placeholder: "Заголовок",
					},
					shortcut: "CMD+SHIFT+H",
				},
				list: {
					class: List,
					inlineToolbar: true,
					shortcut: "CMD+SHIFT+L",
				},
				image: Image,
				quote: {
					class: Quote,
					inlineToolbar: true,
					config: {
						quotePlaceholder: "Введите цитату",
						captionPlaceholder: "Автор цитаты",
					},
					shortcut: "CMD+SHIFT+O",
				},
				marker: {
					class: Marker,
					shortcut: "CMD+SHIFT+M",
				},
				delimiter: Delimiter,
				inlineCode: {
					class: InlineCode,
					shortcut: "CMD+SHIFT+C",
				},
				linkTool: LinkTool,
				embed: {
					class: Embed,
					inlineToolbar: false,
					config: {
						services: {
							youtube: true,
						},
					},
				},
				table: {
					class: Table,
					inlineToolbar: true,
					shortcut: "CMD+ALT+T",
				},

				onReady: function () {
					// saveButton.click();
				},
				onChange: function () {
					console.log("something changed");
				},
			},
			data: null,
		});

		buttonSend.addEventListener("click", function () {
			editor.save().then((savedData) => {
				console.log(savedData);

				create.call(buttonSend, inputCaption, inputLink, savedData, preview, file);
			});
		});

		Modal.Create("Создать новость", body);
	}

	/**
	 * Функция выбора файлов изображения для новости
	 */
	function changeImages() {
		let preview = document.querySelector(".preview-images");
		if (!preview) {
			console.warn("Элемент [.preview-images] не найжен");
			return;
		}
		for (const file of this.files) {
			/**
			 * 1. Контейнер под изображение
			 */
			let div = document.createElement("div");
			div.className = "image";

			/**
			 * 2. Создать элемент для изображения
			 */
			let img = document.createElement("img");
			img.src = window.URL.createObjectURL(file);
			img.alt = file.name;
			img.height = 100;

			/**
			 * 3. Создать label
			 */
			let label = document.createElement("label");

			/**
			 * 4. Создать input + span
			 */
			let input = document.createElement("input");
			input.type = "radio";
			input.dataset.image = file.name;
			input.name = "preview-images";

			let span = document.createElement("span");

			div.append(img, label);
			label.append(input, span);

			preview.append(div);
		}

		let firstImage = preview.querySelector("input");
		firstImage.click();
	}

	return module;
})();
