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

			<div class="ui sixteen wide column">
				<h2 class="ui header">
					<i class="coffee icon"></i>
						<div class="content">
						Quick
						<div class="sub header">Add new information with great speed</div>
					</div>
				</h2>
			</div>

			<div class="ui sixteen wide column">
				<div class="ui form">
					<div class="field">
						<textarea 
							class="quick-note-input" 
							rows="1"
							ref="fastInput"
							v-model="newText"
							v-on:keydown="checkKeyup"
							placeholder="Push to the top of the quick note." 
						></textarea>
					</div>
					<div class="field">
						<div v-on:click="appendQuickNote" class="ui green button">Save (CRTL + Enter)</div>
						<div v-if="quickNoteId" v-on:click="openNoteEdit" class="ui right floated basic button">Edit</div>
					</div>
				</div>
			</div>

			<div class="fun" v-html="savedQuickNoteText"></div>
		</div>
	</div>
</template>
<style type="text/css" scoped>
	.quick-note-input {
		box-sizing: border-box !important;
		resize: none !important;
	}
</style>
<script>

	import axios from 'axios'

	export default {
		data: function(){ 
			return {
				newText: '',
				savedQuickNoteText: '',
				quickNoteId: null
			}
		},
		beforeCreate: function(){
			//
			// Perform Login check
			//
			this.$parent.loginGateway()
		},
		mounted: function(){

			if(this.$refs.fastInput){
				//Load up note text
				this.getQuickNote()

				//Set focus to input pane
				this.$nextTick(() => {
					this.$refs.fastInput.focus()
				})
			}
		},
		computed: {
			loggedIn () {
				return this.$store.getters.getLoggedIn
			}
		},
		methods: {
			openNoteEdit(){
				this.$router.push({'path':'/notes/open/'+this.quickNoteId})
			},
			checkKeyup(event){

				let element = event.target
				let padding = 0

				element.style.height = 'auto';
      			element.style.height = (element.scrollHeight + padding) +'px';

				//If command+enter or control+enter is pressed, submit
				if((event.metaKey || event.ctrlKey) && [13].includes(event.keyCode)){
					this.appendQuickNote()
				}
			},
			appendQuickNote(){

				//Don't submit empty note
				if(this.newText.trim() == ''){ return }

				axios.post('/api/quick-note/update', { 'pushText':this.newText } )
				.then( results => {

					this.newText = '' //Clear text area
					this.$refs.fastInput.style.height = 'auto' //Back to normal size

					this.savedQuickNoteText = results.data.text
					this.quickNoteId = results.data.id
				})
			},
			getQuickNote (){
				axios.post('/api/quick-note/get')
				.then( results => {
					this.savedQuickNoteText = results.data.text
					this.quickNoteId = results.data.id
				})
			},
		}
	}
</script>