<template>
	<div>
		<header>
			<h1>{{ page.name }}</h1>
			<p>{{ page.description }}</p>
			<nuxt-link to="/">back</nuxt-link>
		</header>

		<main>
			<aside>
				<h2>Input</h2>
				<ul>
					<li v-for="input in page.input" :key="input.id">
						<code> {{ input.name }}</code> ({{ input.type.name }})
					</li>
				</ul>
			</aside>
			<section class="arrow">
				→
				<transition name="bounce" mode="out-in">
					<span :key="animationKey">🎈</span>
				</transition>
				→
			</section>
			<aside>
				<h2>Output</h2>
				<ul>
					<li v-for="output in page.output" :key="output.id">
						<code>{{ output.name }}</code> ({{ output.type.name }})
					</li>
				</ul>
			</aside>
		</main>

		<section>
			<h3>Try it:</h3>
			<div class="code">
				<code>
					/functions/{{ page.name }} ?
					<span v-for="(input, index) in page.input" :key="input.id">
						<span v-if="index != 0">&</span
						><input
							v-model="form[input.name]"
							type="text"
							:placeholder="input.name"
						/>
					</span>
				</code>
				<button @click="testApi()">Try</button>
			</div>
			<div class="result">
				<h3>Results</h3>
				<div
					v-for="(output, index) in page.output"
					:key="output.id"
					class="result"
				>
					<code>{{ output.name }}</code
					>: {{ results[index] }}
				</div>
			</div>
		</section>

		<aside>
			<h3>Other functions</h3>
			<ul>
				<li v-for="tool in toolkit" :key="tool.id">
					<nuxt-link :to="`/functions/${tool.name}`">
						{{ tool.name }}
					</nuxt-link>
				</li>
			</ul>
		</aside>
	</div>
</template>

<script>
export default {
	async asyncData({ $strapi, params }) {
		const toolkit = await $strapi.find('functions')
		const query = await $strapi.$functions.find({ name: params.slug })
		const page = query[0]

		const form = {}
		page.input.forEach((input) => (form[input.name] = input.defaultValue))

		return { page, toolkit, form }
	},
	data() {
		return {
			results: [],
			animationKey: 1,
		}
	},

	methods: {
		async testApi() {
			this.results = []
			this.animationKey = Math.random()
			let args = ''
			Object.keys(this.form).forEach((arg) => {
				args += `${arg}=${this.form[arg]}&`
			})
			const data = await this.$strapi.$http.$get(
				`http://localhost:1337/functions/${this.page.name}?${args}`
			)
			this.page.output.forEach((output) => {
				this.results.push(data[output.name])
			})
		},
	},
}
</script>

<style scoped>
main {
	display: flex;
	max-width: 1280px;
	justify-content: center;
	align-items: stretch;
	grid-gap: 24px;
}

main > * {
	padding: 24px;
	margin-top: 24px;
	flex: 1;
	border: 1px solid black;
}
p {
	margin-bottom: 16px;
}

h1 {
	text-transform: capitalize;
}

h2 {
	margin-top: 0;
}

ul {
	padding: 0;
	list-style: none;
}

.arrow {
	align-items: center;
	display: flex;
	justify-content: center;

	font-size: 72px;
}
</style>