<template>

	<div class='container'>

		<div class='header'>
			<div class='title'>{{ gs.room.get('text') ? gs.room.get('text').name : '?' }}</div>
		</div>

		<div class='body'>

			<section class='message-stack' ref='stack'>

				<div class='message' v-for='m in gs.content.messages'>
					<div class='icon' :style='`background-image: url("https://picsum.photos/150/?random&nonce=${m.uid}");`'></div>
					<span class='meta'>
						<span class='author'>{{ gs.content.user(m.uid).username || `guest ${m.uid}` }}</span>
						<span class='date'  >{{ m.ts || 'inconnu' }}</span>
					</span>
					<span class='text'>{{ m.msg }}</span>
				</div>

			</section>

			<section class='message-input'>
				<textarea v-model='message' :placeholder='`Message #${gs.room.get(`text`).name}`' @keydown='keydown' @keyup='keyup'></textarea>
			</section>

		</div>

	</div>

</template><script>
export default {

	name: 'channel-',

	data(){ return {
		gs: gs.get,
		message: '', // message text
		pressed: {
			16: false // SHIFT key
		},
		stack_length: 0

	}; },

	beforeMount(){
		console.warn('beforeMount');
	},

	methods: {

		/* (1) Auto-grow text area
		*
		---------------------------------------------------------*/
		auto_grow(e){

			setTimeout(() => {
				e.target.style.height = '0';
				e.target.style.height = `calc( ${e.target.scrollHeight}px )`;
			}, 1);

		},


		/* (2) Mange Key Down
		*
		---------------------------------------------------------*/
		keydown(e){

			// Manage auto grow
			this.auto_grow(e);

			// register pressed keys
			this.pressed[e.keyCode] = true;

		},


		/* (3) Mange Key Up
		*
		---------------------------------------------------------*/
		keyup(e){

			// unregister pressed keys
			this.pressed[e.keyCode] = false;

			// if not ENTER OR SHIFT -> do nothing
			if( e.keyCode !== 13 || this.pressed[16] )
				return;

			// bufferize message + remove trailing line
			this.message = this.message.replace(/\n*$/, '');

			// send message
			if( !gs.get.content.send_message(this.message) )
				return;

			// empty message
			this.message = '';
			this.auto_grow(e);

		}

	},

	updated(){

		let stack_length = this.$refs.stack.children.length;


		/* (1) If new messages -> scroll to bottom */
		if( stack_length > this.stack_length )
			this.$refs.stack.scrollTop = this.$refs.stack.scrollHeight;

		/* (2) If new messages -> update stack length */
		if( stack_length != this.stack_length )
			this.stack_length = stack_length;

	}

}

</script>