<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="attachment.attachment_content" target="_blank">Stiahnut {{ attachment.attachment_content.split('/').pop().split('?')[0].split('#')[0] }}</a>
					<br>
					<img :src="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
					ref="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>
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)]);

export default {
	name: "Report",
	components: { FullScreenLoader },
	data() {
		return {
			loading: false,
			report_id: this.$route.params.id,
			report: {
				report_id: 0,
				report_title: "Nacitavam report",
				report_description: "...",
				report_status: 4,
				report_group: "--",
				report_priority: 1,
				created_dt: "--",
				ordnum: 0,
			},
			editable: true,
			attachments: [
				{
					attachment_id: 0,
					attachment_type: "comment",
					attachment_content: "Nacitavam report",
					created_dt: "--",
				},
			],
			attachmentNewFiles: null,
			selectedFiles: [],
			selectedFilesContent: [],
		};
	},
	mounted() {
		// console.log(this.report_id);
		this.loadReportData();
	},
	methods: {
		loadReportData() {
			backend.get(this.report_id).then((report) => {
				this.report = report;
				// console.log(this.report);
				this.editable = report.report_status < 4;
			});
			backend.attachmentGetAll(this.report_id).then((attachments) => {
				this.attachments = attachments;
				// console.log(this.attachments);
			});
		},
		onTitleChange(event) {
			backend.update(this.report_id, { report_title: event.target.innerText });
		},
		onDescriptionChange(event) {
			backend.update(this.report_id, {
				report_description: event.target.innerText,
			});
		},
		reportDelete() {
			if (!confirm("Naozaj chcete report zmazať?")) return;
			this.loading = true;
			backend.delete(this.report_id).then(() => {
				this.$router.push("/");
			});
		},
		reportDone() {
			backend.update(this.report_id, {
				report_status: 4,
			}).then(() => {
				jungle.play();
				const confetti = new JSConfetti();
				confetti.addConfetti();
				setTimeout(() => {
					this.$router.push("/");
				}, 3000);
			});
		},
		attachmentAdd() {
			let comment = this.$refs.attachmentNewContent.value;
			if (comment.trim().length > 0) {
				this.loading = true;
				backend
					.attachmentAdd(
						this.report_id,
						"comment",
						this.$refs.attachmentNewContent.value
					)
					.then(() => {
						this.$refs.attachmentNewContent.value = "";
						this.loadReportData();
						this.loading = false;
					});
			}
			if (this.selectedFiles.length > 0) {
				let for_upload = this.selectedFiles.length;
				this.loading = true;
				for (let i = 0; i < this.selectedFiles.length; i++) {
					backend
						.attachmentAdd(this.report_id, "file", {
							'filename': this.selectedFiles[i].name,
							'base64': this.selectedFilesContent[i]
						})
						.then(() => {
							for_upload--;
							if (for_upload == 0) {
								this.selectedFiles = [];
								this.selectedFilesContent = [];
								this.$refs.attachmentNewFiles.value = null;
								this.loadReportData();
								this.loading = false;
							}
						});
				}
			}
		},
		attachmentDelete(attachment) {
			if (!confirm("Naozaj chcete zmazať prilohu?")) return;
			this.loading = true;
			backend.attachmentDelete(attachment.attachment_id).then(() => {
				this.loadReportData();
				this.loading = false;
			});
		},
		updateAttachmentContent(event, attachment) {
			this.loading = true;
			backend
				.attachmentUpdate(attachment.attachment_id, event.target.innerText)
				.then(() => {
					this.loadReportData();
					this.loading = false;
				});
		},
		handleFileUpload(event) {
			const files = event.target.files;
			if (files) {
				for (let i = 0; i < files.length; i++) {
					this.selectedFiles.push(files[i]);
					const reader = new FileReader();
					reader.onload = () => {
						this.selectedFilesContent[i] = reader.result;
					};
					reader.readAsDataURL(files[i]);
				}
			}
		},
		removeFile(index) {
			this.selectedFiles.splice(index, 1);
			this.selectedFilesContent.splice(index, 1);
		},
		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";
			}
		},
		isImageUrl(url) {
			return /\.(jpg|jpeg|png|gif|svg|webp)$/.test(url);
		}
	},
};
</script>
