<template>
  <div
    class='item'
  >
    <div class="column">
      <div class="box">
        <div class="card-content">
          <div class="media">
            <div class="media-content">
              <p class="title is-4"><router-link :to="'/m/' + post.id">{{post.name}}</router-link></p>
              <p class="subtitle is-6">Created by <router-link :to="'/u/' + post.User.username"> @{{post.User.username}}</router-link></p>
            </div>
          </div>

          <div class="content limit">
            {{post.description | truncate(70)}}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ThreadPost',
  props: [
    'post',
    'highlight',
    'showReply',
    'showThread',
    'showSelect',
    'clickForPost',
    'allowQuote'
  ],
  data () {
    let post = this.post

    return {
      hover: false,
      showShareModal: false,
      showReportPostModal: false,
      postURL: `${location.origin}/p/${post.id}`,
      selected: false,

      showQuote: false,
      quoteX: 0,
      quoteY: 0,
      quoteSelection: '',

      postContentHTML: post.content
    }
  },
  computed: {
    username () {
      if(this.post.User) {
        return this.post.User.username
      } else {
        return '[deleted]'}
    },
    showActions () {
      return this.hover || this.showShareModal || this.showReportPostModal
    }
  },
  methods: {
    emitReply () {
      this.showQuote = false;
      this.$emit('reply', this.post.id, this.username, this.quoteSelection);
    },
    setShowQuote () {
      let rootCoords = this.$el.getBoundingClientRect();

      let selection = window.getSelection();
      let coords = selection.getRangeAt(0).getBoundingClientRect();
      let text = selection.toString();

      if(text.length) {
        this.quoteY = coords.top - rootCoords.top - 30;
        this.quoteX = coords.left - rootCoords.left;
        this.quoteSelection =  '> ' + text.replace(/\n/g, '\n> ') + '\n\n';
        this.showQuote = true;
      } else {
        this.showQuote = false;
      }
    },
    setShareModalState (val) {
      this.showShareModal = val
    },
    setShowReportPostModal (val) {
      this.showReportPostModal = val
    },
    goToThread () {
      this.$router.push(`/thread/${this.post.Thread.slug}/${this.post.Thread.id}`)
    },
    goToPost () {
      if(this.clickForPost) {
        this.$router.push(
          '/thread/' +
          this.post.Thread.slug + '/' +
          this.post.Thread.id + '/' +
          this.post.postNumber
        )
      }
    },
    toggleSelected () {
      this.selected = !this.selected

      this.$emit('selected', this.post.id)
    }
  },
  watch: {
    showSelect () {
      if(this.selected) {
        this.$emit('selected', this.post.id)
      }

      this.selected = false
    }
  },
  mounted () {
    this.$linkExpander(this.post.content, v => this.postContentHTML = v);
  }
}
</script>
