<template>
	<div class="ui container">
		<h3>Login</h3>
		<p>Begin the login process by typing your username or email.</p>
		<p>To create an account, type in the username you want to use followed by the password.</p>
		<p>You will remain logged in on this browser, until you log out.</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" v-if="username.length > 0">
					<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>

    
	</div>
</template>

<script>
	
	//ajax calls
	import axios from 'axios';
	import { mapGetters } from 'vuex'

	export default {
	name: 'Login',
		data () {
			return {
				message: 'Login stuff',
				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 => {
					console.log(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
						this.$router.push('/notes')
					}
				})
				.catch(error => {
					console.log('There was an error with log in request')
				})
			}
		},
		computed: {
			...mapGetters([
				'getRudeMessage'
			])
		}
	}
</script>