$(document).ready(function () {
	console.log("[FORM] Load file.js"); // DEBUG
	//update files totals sizes
	const FILES_TO_LOAD = [];
	window.FILES_TO_LOAD = FILES_TO_LOAD;
	const FILE_ARRAY = new Array();

	function onFileChanges() {
		console.log("[FORM] Files to load changed"); // DEBUG
		// cleaning
		$("#files_info").empty();
		FILES_TO_LOAD.length = 0;

		let files = $("#attachments")[0].files;
		// push each files in an array
		for (let i = 0; i < files.length; i++) {
			FILE_ARRAY.push(files[i]);
		}
		$("#attachments").val("");

		let totalSize = 0;
		for (let i = 0; i < FILE_ARRAY.length; i++) {
			let reader = new FileReader();

			reader.onloadend = function () {
				let arrayBuffer = reader.result;
				let byteArray = new Uint8Array(arrayBuffer);
				FILES_TO_LOAD[i] = {name:FILE_ARRAY[i].name, content:byteArray};
			};
			reader.readAsArrayBuffer(FILE_ARRAY[i]);

			let size = FILE_ARRAY[i].size;
			$("#files_info").append(
				`<li>
					<div>
						<p>${FILE_ARRAY[i].name}</p>
						<p>${getFileSize(FILE_ARRAY[i].size)}</p>
						<p id='file-${i}' class='deleteFile'>x</p>
					</div>
				</li>`
			);
			totalSize += size;
		}
		$("#files_size").html(`Total = ${getFileSize(totalSize)}`);

		// add an event listener to deleting file
		$(".deleteFile").click(function (e) {
			let id = e.currentTarget.id;
			let index = id.replace("file-", "");
			FILE_ARRAY.splice(index, 1);
			//update file list
			onFileChanges();
		});
	}

	function getFileSize(size) {
		if (size < 1024) {
			return size + " octets";
		} else if (size >= 1024 && size < 1048576) {
			return (size / 1024).toFixed(1) + " Ko";
		} else if (size >= 1048576) {
			return (size / 1048576).toFixed(1) + " Mo";
		}
	}

	$("#attachments").change(onFileChanges);

	// upload automatic screenshot
	$("#take_screen").click(() => {
		let imgUrl;
		$("#screen_info").empty();
		if (window.javaMySurveyTicket) {
			try {
				imgUrl = window.javaMySurveyTicket.getScreenshot();
				$("#auto_screen").attr("src", `file:///${imgUrl}`);
				$("#cmd_screen").show();
			} catch (error) {
				$("#screen_info").append(`Fail getting screenshot !`);
			}
		} else {
			$("#screen_info").append(`Can't get screenshot !`);
		}
	});

	$("#show_screen").click(() => {
		console.log("[FORM] Show the screenshot"); // DEBUG
		$("#modal-screenshot").show();
	});

	$("#delete_screen").click(() => {
		console.log("[FORM] Delete the screenshot"); // DEBUG
		$("#modal-screenshot").hide();
		$("#auto_screen").attr("src", "");
		$("#cmd_screen").hide();
	});
});
