<template>
	<div>
		<div class="progress {{pstyle}}" role="progressbar" aria-label="Download progress" style="--bs-progress-bar-transition: 0.01s;">
			<div ref="pg" :class="pbstyle" :style="{'width': percent + '%'}">{{status}}</div>
		</div>
		<div class="text-truncate">
			<small>{{srcurl}}</small>
		</div>
		<div v-if="failed" class="alert alert-danger">
			The download has failed with error code <strong>{{errorcode}}</strong>. Please try again.
		</div>
	</div>
</template>

<script>
import { ref } from 'vue/dist/vue.esm-bundler'

export default {
	emits: [
		'complete',
		'failure'
	],
	props: [
		'jobid',
		'url'
	],
	setup() {
		return {
			percent: ref(100),
			pbstyle: ref(""),
			pstyle: ref(""),
			outfile: ref(""),
			srcurl: ref(""),
			failed: ref(false),
			errorcode: ref(""),
			status: ref(""),
		}
	},
	methods: {
		get_status() {
			$.ajax({
				url: "/api/download/" + this.jobid,
				method: "get",
			})	.fail(this.get_status_fail)
				.done(this.got_status);
		},
		get_status_fail(data, status, xhr) {
			this.errorcode = xhr;
			this.failed = true;
		},

		got_status(data, status, xhr) {
			this.update_bar(data);
			if (data.done != data.size) {
				setTimeout(this.get_status, 500);
			} else {
				if (data.size == 0) {
					setTimeout(this.get_status, 2000);
				}
			}
		},

		submit(url) {
			$.ajax({
				url: "/api/download",
				method: "put",
				data: {
					url: this.url
				}
			})	.fail(this.submit_fail)
				.done(this.submitted);
		},

		submit_fail(data, status, xhr) {
			this.errorcode = xhr;
			this.failed = true;
			this.$emit("failed");
		},

		submitted(data, status, xhr) {
			this.update_bar(data);
			setTimeout(this.get_status, 500);
		},
	
		update_bar(data) {
			this.outfile = data.file;
			this.srcurl = data.url;

			if (data.started == 0) {
				this.status = "Queued";
				this.pbstyle = "progress-bar bg-secondary progress-bar-striped progress-bar-animated";
				this.percent = 100;
				return;
			}

			if (data.finished != 0) {
				this.status = "Completed";
				this.pbstyle = "progress-bar bg-success";
				this.percent = 100;
				this.$emit("complete");
				let event = new CustomEvent("complete", { bubbles: true, detail: data });
				document.dispatchEvent(event);
				return;
			}
			
			if (data.size == 0) {
				this.status = "Starting...";
			} else {
				this.percent = data.done / data.size * 100;
				this.pbstyle = "progress-bar bg-primary";
				this.status = Math.round(this.percent) + "%";
			}
		}
	},
	mounted() {
		this.status = "Please wait...";
		this.pbstyle = "progress-bar bg-secondary progress-bar-striped progress-bar-animated";
		this.percent = 100;

		if (this.jobid != "") {
			this.get_status();
		} else if (this.url != "") {
			this.submit(url);
		}
	}
};
</script>
