<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.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([])
		}
	},

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

		updated(d) {
			this.jobs = d;

			var shouldupdate = 0;
			for (var i = 0; i < this.jobs.length; i++) {
				console.log(this.jobs[i]);
				if ((this.jobs[i].finished == 0) && (this.jobs[i].failed == 0)) {
					shouldupdate = 1;
				}
			}
			
			console.log(shouldupdate);
			if (shouldupdate == 1) {
				setTimeout(this.update, 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.updated);
		},
	},

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