<template>
<div class="mk-posts-post" tabindex="-1" :title="title" @keydown="onKeyDown" @dblclick="onDblClick">
	<div class="reply-to" v-if="p.reply">
		<mk-posts-post-sub post="p.reply"/>
	</div>
	<div class="repost" v-if="isRepost">
		<p>
			<a class="avatar-anchor" :href="`/${post.user.username}`" :v-user-preview="post.user_id">
				<img class="avatar" :src="`${post.user.avatar_url}?thumbnail&size=32`" alt="avatar"/>
			</a>
			%fa:retweet%{{'%i18n:desktop.tags.mk-timeline-post.reposted-by%'.substr(0, '%i18n:desktop.tags.mk-timeline-post.reposted-by%'.indexOf('{'))}}<a class="name" :href="`/${post.user.username}`" :v-user-preview="post.user_id">{{ post.user.name }}</a>{{'%i18n:desktop.tags.mk-timeline-post.reposted-by%'.substr('%i18n:desktop.tags.mk-timeline-post.reposted-by%'.indexOf('}') + 1)}}
		</p>
		<mk-time :time="post.created_at"/>
	</div>
	<article>
		<a class="avatar-anchor" :href="`/${p.user.username}`">
			<img class="avatar" :src="`${p.user.avatar_url}?thumbnail&size=64`" alt="avatar" :v-user-preview="p.user.id"/>
		</a>
		<div class="main">
			<header>
				<a class="name" :href="`/${p.user.username}`" :v-user-preview="p.user.id">{{ p.user.name }}</a>
				<span class="is-bot" v-if="p.user.is_bot">bot</span>
				<span class="username">@{{ p.user.username }}</span>
				<div class="info">
					<span class="app" v-if="p.app">via <b>{{ p.app.name }}</b></span>
					<a class="created-at" :href="url">
						<mk-time :time="p.created_at"/>
					</a>
				</div>
			</header>
			<div class="body">
				<div class="text" ref="text">
					<p class="channel" v-if="p.channel"><a :href="`${_CH_URL_}/${p.channel.id}`" target="_blank">{{ p.channel.title }}</a>:</p>
					<a class="reply" v-if="p.reply">%fa:reply%</a>
					<mk-post-html :ast="p.ast" :i="$root.$data.os.i"/>
					<a class="quote" v-if="p.repost">RP:</a>
					<mk-url-preview v-for="url in urls" :url="url" :key="url"/>
				</div>
				<div class="media" v-if="p.media">
					<mk-images :images="p.media"/>
				</div>
				<mk-poll v-if="p.poll" :post="p" ref="pollViewer"/>
				<div class="repost" v-if="p.repost">%fa:quote-right -flip-h%
					<mk-post-preview class="repost" :post="p.repost"/>
				</div>
			</div>
			<footer>
				<mk-reactions-viewer :post="p" ref="reactionsViewer"/>
				<button @click="reply" title="%i18n:desktop.tags.mk-timeline-post.reply%">
					%fa:reply%<p class="count" v-if="p.replies_count > 0">{{ p.replies_count }}</p>
				</button>
				<button @click="repost" title="%i18n:desktop.tags.mk-timeline-post.repost%">
					%fa:retweet%<p class="count" v-if="p.repost_count > 0">{{ p.repost_count }}</p>
				</button>
				<button :class="{ reacted: p.my_reaction != null }" @click="react" ref="reactButton" title="%i18n:desktop.tags.mk-timeline-post.add-reaction%">
					%fa:plus%<p class="count" v-if="p.reactions_count > 0">{{ p.reactions_count }}</p>
				</button>
				<button @click="menu" ref="menuButton">
					%fa:ellipsis-h%
				</button>
				<button @click="toggleDetail" title="%i18n:desktop.tags.mk-timeline-post.detail">
					<template v-if="!isDetailOpened">%fa:caret-down%</template>
					<template v-if="isDetailOpened">%fa:caret-up%</template>
				</button>
			</footer>
		</div>
	</article>
	<div class="detail" v-if="isDetailOpened">
		<mk-post-status-graph width="462" height="130" :post="p"/>
	</div>
</div>
</template>

<script lang="ts">
import Vue from 'vue';
import dateStringify from '../../../common/scripts/date-stringify';
import MkPostFormWindow from './post-form-window.vue';
import MkRepostFormWindow from './repost-form-window.vue';
import MkPostMenu from '../../../common/views/components/post-menu.vue';
import MkReactionPicker from '../../../common/views/components/reaction-picker.vue';

function focus(el, fn) {
	const target = fn(el);
	if (target) {
		if (target.hasAttribute('tabindex')) {
			target.focus();
		} else {
			focus(target, fn);
		}
	}
}

export default Vue.extend({
	props: ['post'],
	data() {
		return {
			connection: null,
			connectionId: null
		};
	},
	computed: {
		isRepost(): boolean {
			return (this.post.repost &&
				this.post.text == null &&
				this.post.media_ids == null &&
				this.post.poll == null);
		},
		p(): any {
			return this.isRepost ? this.post.repost : this.post;
		},
		reactionsCount(): number {
			return this.p.reaction_counts ? Object.keys(this.p.reaction_counts).map(key => this.p.reaction_counts[key]).reduce((a, b) => a + b) : 0;
		},
		title(): string {
			return dateStringify(this.p.created_at);
		},
		url(): string {
			return `/${this.p.user.username}/${this.p.id}`;
		},
		urls(): string[] {
			if (this.p.ast) {
				return this.p.ast
					.filter(t => (t.type == 'url' || t.type == 'link') && !t.silent)
					.map(t => t.url);
			} else {
				return null;
			}
		}
	},
	created() {
		this.connection = this.$root.$data.os.stream.getConnection();
		this.connectionId = this.$root.$data.os.stream.use();
	},
	mounted() {
		this.capture(true);

		if (this.$root.$data.os.isSignedIn) {
			this.connection.on('_connected_', this.onStreamConnected);
		}
	},
	beforeDestroy() {
		this.decapture(true);
		this.connection.off('_connected_', this.onStreamConnected);
		this.$root.$data.os.stream.dispose(this.connectionId);
	},
	methods: {
		capture(withHandler = false) {
			if (this.$root.$data.os.isSignedIn) {
				this.connection.send({
					type: 'capture',
					id: this.post.id
				});
				if (withHandler) this.connection.on('post-updated', this.onStreamPostUpdated);
			}
		},
		decapture(withHandler = false) {
			if (this.$root.$data.os.isSignedIn) {
				this.connection.send({
					type: 'decapture',
					id: this.post.id
				});
				if (withHandler) this.connection.off('post-updated', this.onStreamPostUpdated);
			}
		},
		onStreamConnected() {
			this.capture();
		},
		onStreamPostUpdated(data) {
			const post = data.post;
			if (post.id == this.post.id) {
				this.$emit('update:post', post);
			}
		},
		reply() {
			document.body.appendChild(new MkPostFormWindow({
				propsData: {
					reply: this.p
				}
			}).$mount().$el);
		},
		repost() {
			document.body.appendChild(new MkRepostFormWindow({
				propsData: {
					post: this.p
				}
			}).$mount().$el);
		},
		react() {
			document.body.appendChild(new MkReactionPicker({
				propsData: {
					source: this.$refs.reactButton,
					post: this.p
				}
			}).$mount().$el);
		},
		menu() {
			document.body.appendChild(new MkPostMenu({
				propsData: {
					source: this.$refs.menuButton,
					post: this.p
				}
			}).$mount().$el);
		},
		onKeydown(e) {
			let shouldBeCancel = true;

			switch (true) {
				case e.which == 38: // [↑]
				case e.which == 74: // [j]
				case e.which == 9 && e.shiftKey: // [Shift] + [Tab]
					focus(this.$el, e => e.previousElementSibling);
					break;

				case e.which == 40: // [↓]
				case e.which == 75: // [k]
				case e.which == 9: // [Tab]
					focus(this.$el, e => e.nextElementSibling);
					break;

				case e.which == 81: // [q]
				case e.which == 69: // [e]
					this.repost();
					break;

				case e.which == 70: // [f]
				case e.which == 76: // [l]
					//this.like();
					break;

				case e.which == 82: // [r]
					this.reply();
					break;

				default:
					shouldBeCancel = false;
			}

			if (shouldBeCancel) e.preventDefault();
		}
	}
});
</script>

<style lang="stylus" scoped>
.mk-posts-post
	margin 0
	padding 0
	background #fff
	border-bottom solid 1px #eaeaea

	&:first-child
		border-top-left-radius 6px
		border-top-right-radius 6px

		> .repost
			border-top-left-radius 6px
			border-top-right-radius 6px

	&:last-of-type
		border-bottom none

	&:focus
		z-index 1

		&:after
			content ""
			pointer-events none
			position absolute
			top 2px
			right 2px
			bottom 2px
			left 2px
			border 2px solid rgba($theme-color, 0.3)
			border-radius 4px

	> .repost
		color #9dbb00
		background linear-gradient(to bottom, #edfde2 0%, #fff 100%)

		> p
			margin 0
			padding 16px 32px
			line-height 28px

			.avatar-anchor
				display inline-block

				.avatar
					vertical-align bottom
					width 28px
					height 28px
					margin 0 8px 0 0
					border-radius 6px

			[data-fa]
				margin-right 4px

			.name
				font-weight bold

		> mk-time
			position absolute
			top 16px
			right 32px
			font-size 0.9em
			line-height 28px

		& + article
			padding-top 8px

	> .reply-to
		padding 0 16px
		background rgba(0, 0, 0, 0.0125)

		> mk-post-preview
			background transparent

	> article
		padding 28px 32px 18px 32px

		&:after
			content ""
			display block
			clear both

		&:hover
			> .main > footer > button
				color #888

		> .avatar-anchor
			display block
			float left
			margin 0 16px 10px 0
			position -webkit-sticky
			position sticky
			top 74px

			> .avatar
				display block
				width 58px
				height 58px
				margin 0
				border-radius 8px
				vertical-align bottom

		> .main
			float left
			width calc(100% - 74px)

			> header
				display flex
				margin-bottom 4px
				white-space nowrap
				line-height 1.4

				> .name
					display block
					margin 0 .5em 0 0
					padding 0
					overflow hidden
					color #777
					font-size 1em
					font-weight 700
					text-align left
					text-decoration none
					text-overflow ellipsis

					&:hover
						text-decoration underline

				> .is-bot
					text-align left
					margin 0 .5em 0 0
					padding 1px 6px
					font-size 12px
					color #aaa
					border solid 1px #ddd
					border-radius 3px

				> .username
					text-align left
					margin 0 .5em 0 0
					color #ccc

				> .info
					margin-left auto
					text-align right
					font-size 0.9em

					> .app
						margin-right 8px
						padding-right 8px
						color #ccc
						border-right solid 1px #eaeaea

					> .created-at
						color #c0c0c0

			> .body

				> .text
					cursor default
					display block
					margin 0
					padding 0
					overflow-wrap break-word
					font-size 1.1em
					color #717171

					> .dummy
						display none

					mk-url-preview
						margin-top 8px

					> .channel
						margin 0

					> .reply
						margin-right 8px
						color #717171

					> .quote
						margin-left 4px
						font-style oblique
						color #a0bf46

					code
						padding 4px 8px
						margin 0 0.5em
						font-size 80%
						color #525252
						background #f8f8f8
						border-radius 2px

					pre > code
						padding 16px
						margin 0

					[data-is-me]:after
						content "you"
						padding 0 4px
						margin-left 4px
						font-size 80%
						color $theme-color-foreground
						background $theme-color
						border-radius 4px

				> mk-poll
					font-size 80%

				> .repost
					margin 8px 0

					> [data-fa]:first-child
						position absolute
						top -8px
						left -8px
						z-index 1
						color #c0dac6
						font-size 28px
						background #fff

					> mk-post-preview
						padding 16px
						border dashed 1px #c0dac6
						border-radius 8px

			> footer
				> button
					margin 0 28px 0 0
					padding 0 8px
					line-height 32px
					font-size 1em
					color #ddd
					background transparent
					border none
					cursor pointer

					&:hover
						color #666

					> .count
						display inline
						margin 0 0 0 8px
						color #999

					&.reacted
						color $theme-color

					&:last-child
						position absolute
						right 0
						margin 0

	> .detail
		padding-top 4px
		background rgba(0, 0, 0, 0.0125)

</style>

