<template>
	<div>
		<h1>Create application</h1>
		<div v-if="user">
			<span>{{ instruction }}</span>
			<div class="question_block" v-for="(element, index) in pattern" :key="index">
				<h3 class="question">- {{ element.text }}</h3>
				<span v-if="element.optional"> (Optional)</span>
				<br>
				<ApplicationInputSwitch class="textfield" :highlight="highlight" :type="element.type" :options="element.options" :ref="index"></ApplicationInputSwitch>
				<span class="hint">{{ element.hint }}</span>
			</div>
			<button @click="update">Create/Update</button>
			<span class="error"> {{ error }}</span>
		</div>
		<span v-else>You are not logged in.</span>
	</div>
</template>

<script>
	import ApplicationInputSwitch from '../components/ApplicationInputSwitch.vue'

	export default {
		data () {
			return {
				instruction: '',
				pattern: null,
				highlight: false,
				error: '',
			}
		},
		created () {
			this.core.get('/app-pattern').then((response) => {
				this.instruction = response.data.instruction;
				this.pattern = response.data.fields;
			})
		},
		computed: {
			user() {
				return this.$store.state.user
			},
		},
		methods: {
			isReady() {
				for(let key in this.$refs) {
					//TBI What is that 0
					let el = this.$refs[key][0]

					if(!el.isOkay) {
						return false;
					}
				}

				return true
			},
			getContent() {
				let answers = []
				for(let key in this.$refs) {
					//TBI What is that 0
					answers.push(this.$refs[key][0].getContent())
				}

				return answers
			},
			update() {
				if(this.isReady()) {
					this.core.post('/application', {
						//TODO: Pattern, User-token
						answers: this.getContent(),
						creator: this.user.username,
					}).then((response) => {
						
						console.log('Response: ', response.data);
					});

					this.error = ''
				} else {
					this.highlight = true
					this.error = 'Please fill the required fields'
				}
			},
		},
		components: {
			ApplicationInputSwitch,
		},
	}
</script>

<style scoped>
	.question_block {
		margin: 0.5em 0em;
	}

	.question {
		display: inline;
		color: #ccc;
	}

	.hint {
		font-size: 0.8em;
	}

	.error {
		color: red;
	}
</style>