<style type="text/css" scoped>

</style>

<template>
	<div>

		<div class="ui grid" v-if="this.shareUsername == null">

			<div class="row">
				<div class="eight wide column">
					<div class="ui form">
						<div class="field">
							<input type="text" placeholder="Share with someone" v-model="shareUserInput" v-on:keyup="onKeyup">
						</div>
					</div>
				</div>
				<div class="eight wide column">
					<div class="ui disabled button" v-if="shareUserInput.length == 0">
						Share
					</div>
					<div class="ui green button" v-if="shareUserInput.length > 0" v-on:click="onSubmitClick">
						Share
					</div>
				</div>
			</div>
			<div class="sixteen wide column" v-if="sharedWithUsers.length > 0">
				<h3>Users who can edit this note</h3>
			</div>
			<div class="row" v-for="item in sharedWithUsers">
				<div class="eight wide middle aligned column">
					<h3><i class="green user circle icon"></i>{{item.username}}</h3>
				</div>
				<div class="eight wide column">
					<div class="ui basic compact button" v-on:click="onRevokeAccess(item.noteId)">Remove Access</div>
				</div>
			</div>

		</div>

		<div class="ui grid" v-if="this.shareUsername != null">
			<div class="sixteen wide column">
				Shared with you by <h3><i class="green user circle icon"></i>{{shareUsername}}</h3>
			</div>
		</div>

	</div>
</template>

<script>

	import axios from 'axios'

	export default {
		name: 'ShareNoteComponent',
		props: [ 'noteId', 'rawTextId', 'shareUsername' ],
		data () {
			return {
				sharedWithUsers: [],
				shareUserInput: '',
				debounce: null,
				enableSubmitShare: false,
			}
		},
		beforeMount(){

		},
		mounted(){

			if(this.shareUsername == null){
				this.loadShareList()
			}

		},
		methods: {
			loadShareList(){
				axios.post('/api/note/getshareusers', {'rawTextId':this.rawTextId })
				.then( ({data}) => {
					this.sharedWithUsers = data
				})
				.catch(error => { this.$bus.$emit('notification', 'Failed to Load Shared') })
			},
			onRevokeAccess(sharedNoteId){

				const postData = {
					'noteId': this.noteId,
					'shareUserNoteId': sharedNoteId
				}

				axios.post('/api/note/shareremoveuser', postData)
				.then( ({data}) => {
					console.log(data)
					if(data == true){
						this.loadShareList()
					}
				})
				.catch(error => { this.$bus.$emit('notification', 'Failed to Remove Share User') })
			},
			onKeyup(event){
				if(event.keyCode == 13){
					this.onSubmitClick()
					return
				}
			},
			onSubmitClick(){

				axios.post('/api/note/shareadduser', {'noteId':this.noteId, 'rawTextId':this.rawTextId, 'username':this.shareUserInput })
				.then( ({data}) => {
					if(data == true){
						this.shareUserInput = ''
						this.loadShareList()
					} else {
						this.$bus.$emit('notification', 'User not found')
					}
				})
				.catch(error => { this.$bus.$emit('notification', 'Failed to Add User') })

			},
		}
	}
</script>
