<template>
	<div class="ui basic segment no-fluf-segment">
		<div class="ui grid">
			<div class="ui sixteen wide column">

				<p><b>Create an account:</b> type in the username you want to use followed by the password.</p>
				
				<div class="ui segment" v-on:keyup.enter="submit">
					<div class="ui large form">
						<div class="field">
							<div class="ui input">
								<input v-model="username" type="text" name="email" placeholder="Username or E-mail address" autofocus>
							</div>
						</div>
						<div class="field">
							<div class="ui input">
								<input v-model="password" type="password" name="password" placeholder="Password">
							</div>
						</div>
						<div :class="{ 'disabled':(username.length == 0 || password.length == 0)}" v-on:click="submit" class="ui massive compact fluid green submit button">Login</div>
					</div>
				</div>

				<p>You will remain logged in on this browser, until you log out.</p>

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

<script>
	
	import axios from 'axios';

	export default {
	name: 'Login',
		data () {
			return {
				enabled: false,
				username: '',
				password: ''
			}
		},
		methods: {
			submit(){

				//Both fields are required
				if(this.username <= 0){
					return false
				}
				if(this.password <= 0){
					return false
				}

				let vm = this

				let data = {
					username: this.username,
					password: this.password
				}

				axios.post('/api/user/login', data)
				.then(response => {
					if(response.data.success){
						
						const token = response.data.token
						const username = response.data.username

						vm.$store.commit('setLoginToken', {token, username})

						//Redirect user to notes section after login
						vm.$router.push('/notes')
					} else {
						this.$bus.$emit('notification', 'Incorrect Username or Password')
						vm.$store.commit('destroyLoginToken')
					}
				})
				.catch(error => {
					this.$bus.$emit('notification', 'Incorrect Username or Password')
				})
			}
		}
	}
</script>