<template>
	<div>
		<ul class="list-group">
			<li v-for="job in jobs" :class="'d-flex justify-content-between list-group-item ' + get_group_color(job)">
				<span>
					{{ job.id }} - {{ job.class }} - {{ job.status }}
				</span>
				<small v-if='(job.finished + job.failed) > 0'><button @click='delete_job(job)' class='px-1 py-0 btn btn-danger'><i class='fa fa-close'></i></button></small>
			</li>
		</ul>
	</div>
</template>

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

export default {
	props: [
		"source"
	],

	setup() {
		return {
			jobs: ref([]),
			speed: ref(1000),
			timeout: ref(null),
		}
	},

	methods: {
		init() {
			this.update();
		},

		update() {
			$.ajax({
				url: "/api/jobs/" + this.source,
				method: "GET"
			}).done(this.updated);
		},

		updated(d) {
			this.refresh(d);
			setTimeout(this.update, this.speed);
		},

		refresh(d) {
			this.jobs = d;

			this.speed = 10000;
			for (var i = 0; i < this.jobs.length; i++) {
				if ((this.jobs[i].finished == 0) && (this.jobs[i].failed == 0)) {
					this.speed = 1000;
				}
			}
		},

		get_group_color(j) {
			if (j.failed > 0) {
				return "list-group-item-danger";
			}
			if (j.finished > 0) {
				return "list-group-item-success";
			}
			if (j.started > 0) {
				return "list-group-item-warning";
			}
			return "list-group-item-info";
		},

		delete_job(j) {
			$.ajax({
				url: "/api/jobs/" + j.id,
				method: "DELETE"
			}).done(this.refresh);
		},
	},

	mounted() {
		this.init();
	}
}
</script>
