

<template>
	<div>
		<ul class="list-group">
			<li v-for="i in imports" :class="fancyrow(i)">

				<div class="row">
					<div class="col-1">
						<a v-if="i.revision != null" :href='"/cover/" + i.revision.id + "/cover.jpg"'><img class="w-100" :src='"/cover/" + i.revision.id + "/100/cover.jpg"'></a>
					</div>
					<div class="col-11">
						<div class="row">
							<div class="col-lg-2 col-6">
								<strong v-if="i.imported > 0">Imported</strong>
								<strong v-else-if="i.completed > 0 && i.revision">Completed</strong>
								<strong v-else-if="i.completed > 0 && (!i.revision)">Failed</strong>
								<strong v-else-if="i.started > 0">Processing</strong>
								<strong v-else>Queued</strong>
							</div>
							<div class="col-lg-2 col-6">
								<a v-if="i.revision != null" :href='"/revision/" + i.revision.id'>{{ i.revision.id }}</a>
							</div>
							<div class="col-lg-2 col-3">
								{{ i.guessed_id }}
							</div>
							<div class="col-lg-2 col-3">
								{{ i.guessed_revno }}
							</div>
							<div class="col-lg-2 col-6">
								{{ i.guessed_month }}/{{ i.guessed_year }}
							</div>
						</div>
						<div class="row">
							<div class="col-9 text-truncate">
								{{ i.guessed_title }}
							</div>
							<div class="col-lg-3 col-12 btn-group">
								<button :disabled="busy" class="btn btn-danger" @click="del(i)"><i class="fa-solid fa-trash"></i></button>
								<button :disabled="busy || (i.revision == null)" class="btn btn-secondary" @click="download(i)"><i class="fa-solid fa-download"></i></button>
								<button :disabled="(i.started == 0) || busy" class="btn btn-primary" @click="restart(i)"><i class="fa-solid fa-rotate"></i></button>
								<button class="btn btn-success" :disabled="(i.completed == 0 || (!i.revision)) || busy" @click="import_rev(i)"><i class="fa-solid fa-file-import"></i></button>
							</div>
						</div>
						<div class="row">
							<div class="col-12">
								{{ i.origfile }}
							</div>
						</div>
					</div>
				</div>
			</li>
		</ul>

		<div id="docedit" class="modal" tabindex="-1">
			<div class="modal-dialog modal-xl">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">Create Document</h5>
						<button @click="close" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" :disabled="saving"></button>
					</div>
					<div class="modal-body">
						<div class="row">
							<div class="col-12 alert alert-info">
								{{ i_origfile }}
							</div>
						</div>
						<pdf :rev="i_revision"></pdf>
						<div class="row">
							<div class="col-lg-6 col-12">
								<label for="i_id">Order Number</label>
								<div class="input-group">
									<input @blur="upper_id" @keyup.enter="save" ref="orderno" @keyup.esc="close" type="text" @keyup="find_doc" :class="'form-control' + ((i_id.length <= 25) ? ' is-valid' : ' is-invalid')" name="i_id" v-model="i_id" :disabled="saving">
									<button class="btn btn-secondary" @click="paste_id"><i class="fa-solid fa-paste"></i></button>
								</div>

								<div v-if="newdoc" class="alert alert-warning">
									A new document will be created with this order number.
								</div>

								<div v-else class="alert alert-success">
									This PDF will be added to {{ existing_doc.title }} {{ existing_doc.subtitle }} {{ existing_doc.subsubtitle }} as a new revision.
								</div>

								<div v-if="newdoc">
									<label for="i_title">Title</label>
									<div class="input-group">
										<input ref="rtitle" @keyup.enter="save" @keyup.esc="close" @keyup="try_title" type="text" :class="'form-control' + (i_title == '' ? ' is-invalid' : ' is-valid')" name="i_title" v-model="i_title" :disabled="saving">
										<button class="btn btn-secondary" @click="split_title" title="Split down on cursor position"><i class='fa fa-i-cursor'></i></button>
									</div>
									<label for="i_subtitle">Subtitle</label>
									<div class="input-group">
										<input ref="rsubtitle" @keyup.enter="save" @keyup.esc="close" @keyup="try_subtitle" type="text" class="form-control" name="i_subtitle" v-model="i_subtitle" :disabled="saving">
										<button class="btn btn-secondary" @click="split_subtitle" title="Split down on cursor position"><i class='fa fa-i-cursor'></i></button>
									</div>
									<label for="i_subsubtitle">Sub-subtitle</label>
									<input @keyup.enter="save" @keyup.esc="close" @keyup="try_subsubtitle" type="text" class="form-control" name="i_subsubtitle" v-model="i_subsubtitle" :disabled="saving">
								</div>

							</div>
							<div class="col-lg-6 col-12">

								<label for="i_revno">Revision / Version Number</label>
								<input @keyup.enter="save" @keyup.esc="close" type="text" class="form-control" name="i_revno" v-model="i_revno" :disabled="saving">
								<div class="row">
									<div class="col-6">
										<label for="i_month">Month</label>
										<input @keyup.enter="save" @keyup.esc="close" type="text" class="form-control" name="i_month" v-model="i_month" :disabled="saving">
									</div>

									<div class="col-6">
										<label for="i_year">Year</label>
										<input @keyup.enter="save" @keyup.esc="close" type="text" class="form-control" name="i_year" v-model="i_year" :disabled="saving">
									</div>
								</div>
								<div v-if="newdoc">
									<label for="i_overview">Overview <small>(Markdown supported)</small></label>
									<textarea @keyup.esc="close" name="i_overview" v-model="i_overview" class="form-control w-100" rows="5" :disabled="saving"></textarea>
									<label for="i_products">Products</label>
									<productselector id="ps" v-model="i_products"></productselector>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="col-12">
								<textarea editable="false" v-model="i_covertext" class="form-control"></textarea>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button @click="close" type="button" class="btn btn-secondary" data-bs-dismiss="modal" :disabled="saving">Close</button>
						<button @click="save" type="button" class="btn btn-primary" :disabled="saving || (newdoc && ((i_products == '') || (i_title == '')))">
							<span v-if="!saving">Save changes</span>
							<span class="spinner-border spinner-border-sm" role="status" v-if="saving"></span>
							<span v-if="saving" class="mx-1">Saving...</span>
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

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

export default {
	props: [
	],

	setup() {
		return {
			imports: ref([]),
			busy: ref(false),
			i_products: ref(""),
			i_id: ref(""),
			i_title: ref(""),
			i_subtitle: ref(""),
			i_subsubtitle: ref(""),
			i_revno: ref(""),
			i_month: ref(0),
			i_year: ref(0),
			i_overview: ref(""),
			i_cover: ref(""),
			i_fullcover: ref(""),
			i_origfile: ref(""),
			i_covertext: ref(""),
			i_revision: ref(0),

			triglock: ref(false),

			saving: ref(false),

			importing: ref({
				id: 0
			}),
			
			newdoc: ref(true),
			existing_doc: ref({
				title: '',
				subtitle: '',
				subsubtitle: '',
			}),
			timer: ref(null),
			zoom: ref(null),

			fsel_start: ref(0),
			fsel_end: ref(0),
			fsel_el: ref(null),
			keytimer : ref(false),
		}
	},

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

		focus() {
			this.$refs.rtitle.focus();
			this.zoom = new ImageZoom(document.getElementById("cover"), {
				fillContainer: true,
				offset: { vertical: 0, horizontal: 10 },
				zoomStyle: "z-index: 10;",
			});
		},

		update() {
			this.timer = false;
			$.ajax({
				url: "/api/imports",
				method: "GET"
			}).done(this.got_update);
		},

		got_update(data) {
			this.imports = data;
			this.busy = false;
		
			var r = 0;

			for (var i = 0; i < this.imports.length; i++) {
				if (this.imports[i].completed == 0) {
					r = 1;
				}
			}

			if (r) {
				if (this.timer) {
					clearTimeout(this.timer);
					this.timer=null;
				}
				this.timer = setTimeout(this.update, 1000);
			}
		},

		del(rev) {
			this.busy = true;
			$.ajax({
				url: "/api/import/" + rev.id,
				method: "DELETE"
			}).done(this.got_update);
		},

		restart(rev) {
			this.busy = true;
			$.ajax({
				url: "/api/import/" + rev.id,
				method: "POST",
				data: {
					started: 0,
					completed: 0,
					imported: 0,
				}
			}).done(this.got_update);
		},

		import_rev(rev) {
			this.importing = rev;
			this.i_id = rev.guessed_id;
			this.i_title = rev.guessed_title;
			this.i_revno = rev.guessed_revno;
			this.i_subtitle = "";
			this.i_subsubtitle = "";
			this.i_month = rev.guessed_month;
			this.i_year = rev.guessed_year;
			this.i_overview = rev.overview;
			this.i_products = "";
			this.i_cover = "/cover/" + rev.revision.id + "/cover.jpg";
			this.i_fullcover = "/cover/" + rev.revision.id + "/cover.jpg";
			this.i_origfile = rev.origfile;
			this.i_covertext = rev.covertext;
			this.i_revision = rev.revision.id;
			this.find_doc();

$(document).on('hide.bs.modal', '#docedit', function(e) {alert("doc"); });
$('#docedit').on('hide.bs.modal', function(e) {alert("modal"); });

            $('#docedit').show();
			setTimeout(this.focus, 10);
		},

		test(e) {
			console.log(e);
		},

		close() {
			$('#docedit').hide();
		},

		save() {

			if (this.busy) return;
			if (this.saving) return;
			if (this.newdoc && (this.i_products == '')) return;
			if (this.newdoc && (this.i_title == '')) return;

			this.busy = true;
			this.saving = true;
			$.ajax({
				url: "/api/import/" + this.importing.id ,
				method: "PUT",
				data: {
					internal_id: this.i_id,
					title: this.i_title,
					subtitle: this.i_subtitle,
					subsubtitle: this.i_subsubtitle,
					month: this.i_month,
					year: this.i_year,
					overview: this.i_overview,
					products: this.i_products,
					revno: this.i_revno,	
				}
			}).done(this.saved);
		},
		
		saved(data) {
			this.got_update(data);
			this.saving = false;
			$('#docedit').hide();
			delete this.zoom;
		},

		find_doc() {

			var i_id = this.i_id.toUpperCase();
			
			$.ajax({
				url: "/api/documentbyid/" + i_id,
				method: "GET"
			}).done(this.got_doc);
		},

		got_doc(data) {
			if (data == false) {
				this.newdoc = true;
			} else {
				this.newdoc = false;
				this.existing_doc = data;
			}
		},

		fancyrow(i) {
			if (i.completed > 0) {
				if (!i.revision) {
					return "list-group-item list-group-item-danger";
				} else {
					return "list-group-item list-group-item-success";
				}
			}
			if (i.started > 0) return "list-group-item list-group-item-warning";
			if (i.queued > 0) return "list-group-item list-group-item-primary";
			return "list-group-item";
		},

        get_caret_position(oField) {
            // Initialize
            var iCaretPos = 0;

            if (document.selection) {

                // Set focus on the element
                oField.focus();

                // To get cursor position, get empty selection range
                var oSel = document.selection.createRange();

                // Move selection start to 0 position
                oSel.moveStart('character', -oField.value.length);

                // The caret position is selection length
                iCaretPos = oSel.text.length;
            } else if (oField.selectionStart || oField.selectionStart == '0') {
                iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
            }
            return iCaretPos;
        },

		select_to_end(oField, from) {
			if (document.selection) {
				oField.focus();
				var oSel = document.selection.createRange();
				oSel.moveStart('character', from);
				oSel.moveEnd('character', oField.value.length);
			} else {
				oField.setSelectionRange(from, oField.value.length);
			}
		},

        split_title() {
            var pos = this.get_caret_position(this.$refs.rtitle);
            var l = this.i_title.substring(0, pos);
            var r = this.i_title.substring(pos);
            this.i_title = l;
            this.i_subtitle = r;
        },

        split_subtitle() {
            var pos = this.get_caret_position(this.$refs.rsubtitle);
            var l = this.i_subtitle.substring(0, pos);
            var r = this.i_subtitle.substring(pos);
            this.i_subtitle = l;
            this.i_subsubtitle = r;
        },

		upper_id() {
			this.i_id = this.i_id.toUpperCase();
		},

		paste_id() {
			if (navigator.clipboard) {
				navigator.clipboard.readText().then(this.do_set_id);
			}
		},

		do_set_id(data) {
			this.i_id = data;
			this.find_doc();
		},

		download(data) {
			document.location="/pdf/" + data.revision.id + "/download/doc.pdf";
		},

		try_title(e) {
			if (e.key == "Shift") return;
			if (e.key == "ArrowLeft") return;
			if (e.key == "ArrowRight") return;
			if (e.key == "ArrowUp") return;
			if (e.key == "ArrowDown") return;
			if (e.key == "Backspace") return;
			if (this.triglock) return;

			if (this.keytimer) {
				clearTimeout(this.keytimer);
			}
			this.keytimer = setTimeout(this.try_title2, 250);
		},

		try_title2() {
			this.keytimer = false
			$.ajax({
				url: "/api/search/prefix",
				method: "POST",
				data: {
					title: this.i_title
				}
			}).done(this.fill_title);
		},

		fill_title(data, status) {
			if (status == "success") {
				this.triglock = true;
				this.fsel_start = this.get_caret_position(this.$refs.rtitle);
				this.fsel_el = this.$refs.rtitle;
				this.i_title = data;
				this.triglock = false;
				setTimeout(this.fsel, 10);
			}
		},

		try_subtitle(e) {
			if (e.key == "Shift") return;
			if (e.key == "ArrowLeft") return;
			if (e.key == "ArrowRight") return;
			if (e.key == "ArrowUp") return;
			if (e.key == "ArrowDown") return;
			if (e.key == "Backspace") return;
			if (this.triglock) return;

			if (this.keytimer) {
				clearTimeout(this.keytimer);
			}
			this.keytimer = setTimeout(this.try_subtitle2, 250);
		},

		try_subtitle2() {
			this.keytimer = false
			$.ajax({
				url: "/api/search/prefix",
				method: "POST",
				data: {
					title: this.i_subtitle
				}
			}).done(this.fill_subtitle);
		},

		fill_subtitle(data, status) {
			if (status == "success") {
				this.triglock = true;
				this.fsel_start = this.get_caret_position(this.$refs.rsubtitle);
				this.fsel_el = this.$refs.rsubtitle;
				this.i_subtitle = data;
				this.triglock = false;
				setTimeout(this.fsel, 10);
			}
		},

		try_subsubtitle(e) {
			if (e.key == "Shift") return;
			if (e.key == "ArrowLeft") return;
			if (e.key == "ArrowRight") return;
			if (e.key == "ArrowUp") return;
			if (e.key == "ArrowDown") return;
			if (e.key == "Backspace") return;
			if (this.triglock) return;

			if (this.keytimer) {
				clearTimeout(this.keytimer);
			}
			this.keytimer = setTimeout(this.try_subsubtitle2, 250);
		},

		try_subsubtitle2() {
			this.keytimer = false
			$.ajax({
				url: "/api/search/prefix",
				method: "POST",
				data: {
					title: this.i_subsubtitle
				}
			}).done(this.fill_subsubtitle);
		},

		fill_subsubtitle(data, status) {
			if (status == "success") {
				this.triglock = true;
				this.fsel_start = this.get_caret_position(this.$refs.rsubsubtitle);
				this.fsel_el = this.$refs.rsubsubtitle;
				this.i_subsubtitle = data;
				this.triglock = false;
				setTimeout(this.fsel, 10);
			}
		},

		fsel() {
			this.select_to_end(this.fsel_el, this.fsel_start);
		},


	

	},

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