<template>
  <div
    v-infinite-scroll="loadMore"
    infinite-scroll-disabled="disableInfinite"
    class="social-feed-listing"
  >
    <transition name="fadeIn" mode="out-in">
      <!-- First time loader -->
      <div
        v-if="loading && firstLoading"
        key="loader"
        class="listing__filter-loader df-center-x"
      >
        <loader-ui />
      </div>

      <!-- Infinite content -->
      <div
        v-else-if="feeds.length"
        ref="masonry"
        key="content"
        class="listing__content"
      >
        <!-- Cards -->
        <div
          v-for="feed of feeds"
          :key="feed.id"
          class="feed-card-wrapper grid-item"
          :class="randItemClass"
        >
          <Link
            :href="`https://twitter.com/${feed.account_name}/status/${feed.import_id}`"
            :inline="false"
          >
            <div class="feed-card">
              <div v-html="feed.content" />

              <div class="feed-card__footer">
                <div :style="background(feed)" class="feed-card__footer__img" />

                <div class="feed-card__footer__name">
                  <strong>{{ feed.account.name }}</strong>

                  <div>@{{ feed.account_name }}</div>
                </div>

                <div
                  class="feed-card__footer__time"
                  v-html="timestampToString(feed.date)"
                />
              </div>
            </div>
          </Link>
        </div>
      </div>
    </transition>

    <!-- More is loading -->
    <transition v-if="loading && !firstLoading" name="fadeIn">
      <loader-ui class="listing__content-loader" />
    </transition>
  </div>
</template>

<script>
import Masonry from 'masonry-layout'

import { Link } from 'inside-collection/components'

const ITEM_CLASSES = [
  'grid-item--width2 grid-item--height2',
  'grid-item--width2',
  'grid-item--height2'
]

const randomInt = (min = 1, max = ITEM_CLASSES.length) =>
  Math.floor(Math.random() * (max - min) + min)

const randItemClass = () => ITEM_CLASSES[randomInt()]

export default {
  components: { Link },
  data: () => ({
    firstLoading: true,
    loading: false,
    reachedEnd: false,
    feeds: []
  }),
  computed: {
    randItemClass,
    // Disable infinite scroll while loading and when the end is reached
    disableInfinite() {
      return this.loading || this.reachedEnd
    },
    background() {
      return feed =>
        this.getCheckedData(feed, ['account', 'avatar_url'])
          ? {
              'background-image': `url(${this.getCheckedData(feed, [
                'account',
                'avatar_url'
              ]).replace('_normal', '')}`
            }
          : ''
    }
  },
  mounted() {
    this.$nextTick(() => this.layout())
  },
  updated() {
    this.layout()
  },
  methods: {
    layout() {
      this._masonry = new Masonry(this.$refs.masonry, {
        itemSelector: '.grid-item',
        columnWidth: 160,
        percentPosition: true
      })
    },
    // Load more items
    loadMore() {
      this.loading = true

      const params = { limit: 20 }
      if (this.feeds.length) {
        params.max_date = this.feeds[this.feeds.length - 1].date
      }

      this.get('feed/social', { params }).then(
        res => {
          this.loading = false
          this.firstLoading = false

          // Accounts by type + name
          let accounts = {}
          for (let account of res.data.accounts) {
            accounts[account.feed_type.toLowerCase() + account.title] = account
          }

          // Add new feeds
          const count = this.feeds.length
          for (let feed of res.data.feeds) {
            if (this.feeds.find(f => f.id === feed.id)) continue
            feed.account =
              accounts[feed.account_type.toLowerCase() + feed.account_name]
            if (!feed.account) continue
            this.feeds.push(feed)
          }

          // No feed added
          if (count === this.feeds.length || res.data.feeds.length < 20) {
            this.reachedEnd = true
          }
        },
        err => {
          console.error(err)
        }
      )
    },
    // Convert php timestamp to readable date
    timestampToString(timestamp) {
      // Diff in seconds
      const diff = Date.now() / 1000 - timestamp
      if (diff < 3600) {
        return Math.ceil(diff / 60) + 'm'
      }
      if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + 'h'
      }

      // Diff in month
      const date = new Date(timestamp * 1000)
      const now = new Date()
      const pad = n => (n > 9 ? n : '0' + n)

      let res = pad(date.getDate()) + '/' + pad(date.getMonth() + 1)
      if (now.getFullYear() !== date.getFullYear()) {
        res += '<br>' + date.getFullYear()
      }
      return res
    }
  }
}
</script>

<style scoped lang="scss">
.social-feed-listing {
  .loader-ui {
    margin: 0 auto;
  }

  .grid-item {
    float: left;
  }
  .grid-item--width2 {
    width: 320px;
  }
  .grid-item--width3 {
    width: 480px;
  }
  .grid-item--width4 {
    width: 640px;
  }

  .grid-item--height2 {
    height: 200px;
  }
  .grid-item--height3 {
    height: 260px;
  }
  .grid-item--height4 {
    height: 360px;
  }
}
</style>
