import padliographyStore from "./PadStore.js";

export default {
	setup() {
		const { ref, computed } = Vue;

		const title = ref("");
		const link = ref("");
		const overview = ref("");
		const categories = ref([""]);
		const date = ref(null);

		const { padStore, currentPage, baseUrl } = padliographyStore();

		const sent = ref(false);
		const disabled = computed(() => {
			return [title, overview, overview, categories].some((input) => input.value == "");
		});

		const newPad = function () {
			let name = title.value.trim().replaceAll(" ", "_");
			let url = `https://pad.xpub.nl/p/${name}`;
			window.open(url);
			return url;
		};

		const submit = function () {
			if (link.value == "") {
				link.value = newPad();
			}

			const pad = {
				title: title.value.trim(),
				link: link.value,
				overview: overview.value,
				categories: categories.value,
				date: date.value,
			};
			padStore.value.unshift(pad);

			pad.categories = pad.categories.join(", ");

            fetch(`${baseUrl.value}/api/${currentPage.value}/`, {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(pad),
			});
			sent.value = true;

			title.value = "";
			link.value = "";
			overview.value = "";
			categories.value = [""];
			date.value = null;
		};

		return {
			title,
			link,
			overview,
			categories,
			date,
			submit,
			newPad,
			sent,
			disabled,
			padStore,
		};
	},

	template: `
    
        <div class='app-form'>
			<h2>Add a new pad</h2>
			<input class='title' type="text" v-model="title" placeholder="Title" />
			<input class='link' type="text" v-model="link" placeholder="URL" />

			<input class='overview' type="text" v-model="overview" placeholder="Overview" />
			<input class='categories' type="text" v-model="categories[index]" placeholder="Category" v-for="(category, index) in categories" :key="index"/> 
			<button class="add" @click="categories.push('')">+</button>
			<input class='date'  type="date" v-model="date" placeholder="Date" />
             
			<button @click="submit" class="submit">Insert</button>
        </div>
    
    
    `,
};
