<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="folder open outline icon"></i>
						<div class="content">
						Files
						<div class="sub header">Uploaded Files and Websites from notes.</div>
					</div>
				</h2>
			</div>

			<div class="sixteen wide column" v-if="searchParams.noteId">
				<div class="ui green button" v-on:click="clearNote">
					<i class="chevron circle left icon"></i>
					Show All Attachments
				</div>
				<div class="ui green button" v-on:click="openNote">
					<i class="file outline icon"></i>
					Open Note
				</div>
			</div>

			<div class="sixteen wide column" v-if="searchParams['noteId'] && attachments.length == 0">
				<h3>There are no attachments for this note.</h3>
				<h3>Attachments are links or files added to the note.</h3>
			</div>

			<div class="sixteen wide column">
				<attachment-display 
					v-for="item in attachments" 
					:item="item"
					:key="item.id"
					:search-params="searchParams"
				/>
			</div>
			
		</div>
	</div>
</template>
<script>

	import axios from 'axios'

	export default {
		components: {
			'attachment-display': require('@/components/AttachmentDisplayCard').default,
		},
		data: function(){ 
			return {
				attachments: [],
				searchParams: {}
			}
		},
		beforeCreate: function(){
			//
			// Perform Login check
			//
			this.$parent.loginGateway()
		},
		mounted: function(){

			//Mount notes on load if note ID is set
			this.openNoteAttachments()
			this.searchAttachments()
		},
		watch:{
			$route (to, from){
				//Open or close notes on route change
				this.openNoteAttachments()
				this.searchAttachments()
			}
		},
		methods: {
			openNoteAttachments(){
				if(this.$route.params && this.$route.params.id){
					const inputNoteId = this.$route.params.id
					this.searchParams['noteId'] = inputNoteId
				}
			},
			openNote(){
				const noteId = this.searchParams['noteId']
				this.$router.push('/notes/open/'+noteId)
			},
			clearNote(){
				this.$router.push('/attachments/')
				delete this.searchParams.noteId
			},
			searchAttachments (){

				axios.post('/api/attachment/search', this.searchParams)
				.then( results => {
					this.attachments = results.data
				})
			},
		}
	}
</script>
<style type="text/css" scoped>
	.attachment-display-area {
		width: 100%;
		margin-top: 15px;
		box-sizing: border-box;
		padding: 0 5%;
	}
</style>