<template>
	<FullScreenLoader v-if="loading" />

	<div id="report">
		<div class="report-header">
			<div>
				<span>Report</span>
				<strong>{{ report_id }}</strong>
			</div>
			<div>
				<span>Vytvorene</span>
				<strong>{{ report.created_dt }}</strong>
			</div>
			<div>
				<span>Stav</span>
				<strong>{{ report.report_status }}</strong>
			</div>
			<div>
				<span>Priorita</span>
				<strong>{{ report.report_priority }}</strong>
			</div>
			<div>
				<span>Skupina</span>
				<strong>{{ report.report_group }}</strong>
			</div>
			<div>
				<button @click="reportDelete">
					<font-awesome-icon :icon="['fas', 'trash-can']" /> Zmazať
				</button>
			</div>
			<div v-if="editable">
				<button @click="reportDone">
					<font-awesome-icon :icon="['fas', 'circle-check']" /> Hotovo, presunut do archivu
				</button>
			</div>
		</div>
		<h1 :contenteditable="editable" @blur="onTitleChange" ref="reportTitle">
			{{ report.report_title }}
		</h1>
		<p
			class="description"
			:contenteditable="editable"
			@blur="onDescriptionChange"
			ref="reportDescription"
		>
			{{ report.report_description }}
		</p>
		<div class="attachments">
			<div
				class="attachment"
				v-for="attachment in attachments"
				:key="attachment.attachment_id"
			>
				<div class="attachment-header">
					<span class="created" title="Vytvorene"
						><font-awesome-icon :icon="['fas', 'calendar-days']" />
						{{ attachment.created_dt }}</span
					>
					<span
						class="updated"
						v-if="attachment.updated_dt"
						title="Posledná zmena"
						><font-awesome-icon :icon="['fas', 'pen']" />
						{{ attachment.updated_dt }}</span
					>
					<span class="author"
						><font-awesome-icon :icon="['fas', 'user']" />
						{{ attachment.attachment_author }}</span
					>
					<span class="actions">
						<button @click="attachmentDelete(attachment)">
							<font-awesome-icon :icon="['fas', 'circle-xmark']" /> Odstranit
						</button>
					</span>
				</div>
				<div
					v-if="attachment.attachment_type == 'comment'"
					class="attachment-content"
					:contenteditable="attachment.editable ?? false"
					@dblclick="attachment.editable = true && editable"
					@blur="
						attachment.editable = false;
						updateAttachmentContent($event, attachment);
					"
				>
					{{ attachment.attachment_content }}
				</div>
				<div
					v-else-if="attachment.attachment_type == 'file'"
					class="attachment-file"
				>
					<a :href="backend.endpoint + attachment.attachment_content" target="_blank">Stiahnut {{ attachment.attachment_content.split('/').pop().split('?')[0].split('#')[0] }}</a>
					<br>
					<img :src="backend.endpoint + attachment.attachment_content" v-if="isImageUrl(attachment.attachment_content)" />
				</div>
				<div v-else class="attachment-content">
					Neznamy typ prilohy: <strong>{{ attachment.attachment_type }}</strong>
				</div>
			</div>
		</div>
		<div class="attachment-new" v-if="editable">
			<div class="form-group">
				<label for="description">Nový komentár:</label>
				<textarea
					v-model="attachmentNewContent"
					rows="5"
					class="form-control"
					placeholder="Nove zistenia alebo riesenia"
					required
				></textarea>
			</div>
			<div class="form-group">
				<label for="files">Prílohy:</label>
				<input
					type="file"
					id="files"
					ref="attachmentNewFiles"
					@change="handleFileUpload"
					multiple
					class="form-control file-input"
				/>
				<div class="selected-files" v-if="selectedFiles.length > 0">
					<p>Vybrané súbory:</p>

					<p v-for="(file, index) in selectedFiles" :key="index">
						<button
							type="button"
							class="remove-file"
							@click="removeFile(index)"
						>
							<font-awesome-icon :icon="['fas', 'circle-xmark']" /> Odober súbor
						</button>
						&nbsp;&nbsp;
						{{ file.name }} ({{ formatFileSize(file.size) }})
					</p>
				</div>
			</div>
			<div class="form-actions">
				<button @click="attachmentAdd">
					<font-awesome-icon :icon="['fas', 'circle-plus']" /> Pridať
				</button>
			</div>
		</div>
	</div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { router } from "../router";
import backend from "../backend";
import FullScreenLoader from "../components/FullScreenLoader.vue";
import JSConfetti from 'js-confetti'

let tadas = ['/sounds/tada.mp3', '/sounds/tada2.mp3', '/sounds/crazy-phrog-short.mp3'];
const jungle = new Audio(tadas[Math.floor(Math.random() * tadas.length)]);

const loading = ref(false);
const report_id = router.currentRoute.value.params.id;
const report =  ref({
	report_id: 0,
	report_title: "Nacitavam report",
	report_description: "...",
	report_status: 4,
	report_group: "--",
	report_priority: 1,
	created_dt: "--",
	ordnum: 0,
});
const editable = ref(true);
const attachments = ref([
	{
		attachment_id: 0,
		attachment_type: "comment",
		attachment_content: "Nacitavam report",
		created_dt: "--",
	},
]);
const attachmentNewContent = ref(null);
const attachmentNewFiles = ref(null);
const selectedFiles = ref([]);
const selectedFilesContent = ref([]);

onMounted(() => {
	// console.log(report_id);
	loadReportData();
});

function loadReportData() {
	backend.get(report_id).then((response) => {
		report.value = response.data;
		// console.log(report);
		editable.value = response.data.report_status < 4;
	});
	backend.attachmentGetAll(report_id).then((response) => {
		attachments.value = response.data;
		// console.log(attachments);
	});
}

function onTitleChange(event) {
	backend.update(report_id, { report_title: event.target.innerText });
}

function onDescriptionChange(event) {
	backend.update(report_id, {
		report_description: event.target.innerText,
	});
}

function reportDelete() {
	if (!confirm("Naozaj chcete report zmazať?")) return;
	loading.value = true;
	backend.delete(report_id).then(() => {
		router.push("/");
	});
}

function reportDone() {
	backend.update(report_id, {
		report_status: 4,
	}).then(() => {
		jungle.play();
		const confetti = new JSConfetti();
		confetti.addConfetti();
		setTimeout(() => {
			router.push("/");
		}, 3000);
	});
}

function attachmentAdd() {
	let comment = attachmentNewContent.value;
	if (comment.trim().length > 0) {
		loading.value = true;
		backend
			.attachmentAdd(
				report_id,
				"comment",
				attachmentNewContent.value
			)
			.then(() => {
				attachmentNewContent.value = "";
				loadReportData();
				loading.value = false;
			});
	}
	if (selectedFiles.value.length > 0) {
		let for_upload = selectedFiles.value.length;
		loading.value = true;
		for (let i = 0; i < selectedFiles.value.length; i++) {
			backend
				.attachmentAdd(report_id, "file", {
					'filename': selectedFiles.value[i].name,
					'base64': selectedFilesContent.value[i]
				})
				.then(() => {
					for_upload--;
					if (for_upload == 0) {
						selectedFiles.value = [];
						selectedFilesContent.value = [];
						attachmentNewFiles.value = null;
						loadReportData();
						loading.value = false;
					}
				});
		}
	}
}

function attachmentDelete(attachment) {
	if (!confirm("Naozaj chcete zmazať prilohu?")) return;
	loading.value = true;
	backend.attachmentDelete(attachment.attachment_id).then(() => {
		loadReportData();
		loading.value = false;
	});
}

function updateAttachmentContent(event, attachment) {
	loading.value = true;
	backend
		.attachmentUpdate(attachment.attachment_id, event.target.innerText)
		.then(() => {
			loadReportData();
			loading.value = false;
		});
}

function handleFileUpload(event) {
	const files = event.target.files;
	if (files) {
		for (let i = 0; i < files.length; i++) {
			selectedFiles.value.push(files[i]);
			const reader = new FileReader();
			reader.onload = () => {
				selectedFilesContent.value[i] = reader.result;
			};
			reader.readAsDataURL(files[i]);
		}
	}
}

function removeFile(index) {
	selectedFiles.value.splice(index, 1);
	selectedFilesContent.value.splice(index, 1);
}

function formatFileSize(size) {
	if (size < 1024) {
		return size + " B";
	} else if (size < 1024 * 1024) {
		return (size / 1024).toFixed(2) + " KB";
	} else {
		return (size / (1024 * 1024)).toFixed(2) + " MB";
	}
}

function isImageUrl(url) {
	return /\.(jpg|jpeg|png|gif|svg|webp)$/.test(url);
}

</script>
