<style lang="scss">
</style>

<template>
	<div id="loginContainer">
		<modal id="login" :shown="true">
			<div class="lpModalHeader">
				<h2>Password required!</h2>
			</div>

			<form @submit.prevent="login">
				<p v-if="message" class="lpSuccess">
					{{ message }}
				</p>
				<div class="lpFields">
					<input v-model="password" v-select-on-bus="'focus-login-password'" type="password" placeholder="Password" name="password" class="password">
				</div>

				<errors :errors="errors" />

				<div class="lpButtons">
					<button class="lpButton">
						Login
						<spinner v-if="fetching" />
					</button>
				</div>
			</form>
		</modal>

		<globalAlerts />
	</div>
</template>

<script>
import globalAlerts from '../components/globalAlerts.vue';
import errors       from '../components/errors.vue';
import spinner      from '../components/spinner.vue';
import modal        from '../components/modal.vue';

import dataTypes    from '../dataTypes.js';

const Library = dataTypes.Library;

export default {
	name: 'Login',
	components: {
		errors,
		spinner,
		globalAlerts,
		modal,
	},
	props: ['message'],
	data() {
		return {
			fetching: false,
			errors: [],
			password: '',
		};
	},
	beforeMount() {
		if (this.$store.state.library) {
			router.push('/editor');
		}
	},
	mounted() {
		bus.$emit('focus-login-password');
	},
	methods: {
		login() {
			this.errors = [];

			if (!this.password) {
				this.errors.push({ field: 'password', message: 'Please enter a password.' });
			}

			if (this.errors.length) {
				return;
			}

			this.fetching = true;

			return fetchJson('/getLibrary', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				credentials: 'same-origin',
				body: JSON.stringify({ password: this.password }),
			})
				.then((response) => {
					this.$store.commit('setSyncToken', response.syncToken);
					if (response.library !== "") {
						this.$store.commit('loadLibraryData', response.library);
					} else {
						let freshLibrary = JSON.stringify(new Library().save());
						this.$store.commit('loadLibraryData', freshLibrary);
					}
					this.$router.push('/editor');
					this.fetching = false;
				})
				.catch((err) => {
					this.errors = err;
					bus.$emit('focus-login-password');
					this.password = '';
					this.fetching = false;
				});
		},
	},
};
</script>
