<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 grid-item--width2"
        >
          <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">
@use '@inside-library/styles/mixins/partials/common-mixin' as *;

.social-feed-listing {
  .loader-ui {
    margin: 0 auto;
  }

  .grid-item {
    float: left;
  }
  .grid-item--width2 {
    width: 320px;
  }

  .feed-card {
    width: 100%;
    padding: var(--spacing-m) var(--spacing-xl) var(--spacing-xl);
    background: var(--color-light);
    box-shadow: var(--shadow-default);
    font-size: var(--font-size-h5);

    &-wrapper {
      padding: 15px;

      @include tablet {
        width: 50%;
      }

      @include mobile {
        width: 100%;
      }
    }

    &-parent {
      width: 100%;
    }

    a.video,
    a.photo {
      margin-top: var(--spacing-m);
      display: block;
    }

    a.video {
      position: relative;
      &::before,
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

      &::before {
        width: 40px;
        height: 40px;
        background: var(--color-light);
        border-radius: 100%;
      }

      &::after {
        width: 0;
        height: 0;
        border-top: 12px solid transparent;
        border-bottom: 13px solid transparent;
        border-left: 13px solid black;
        transform: translate(-5px, -50%);
      }
    }

    &__footer {
      margin-top: var(--spacing-m);
      display: flex;

      &__img {
        width: 55px;
        height: 55px;
        border-radius: 100%;
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        flex-shrink: 0;
      }

      &__name {
        flex: auto;
        padding: var(--spacing-xs) var(--spacing-m);
        place-self: flex-end;

        @include fontSize(15);

        strong {
          font-weight: 600;
        }

        div {
          color: var(--color-grey-500);
          margin-top: var(--spacing-xs);
        }
      }

      &__time {
        color: var(--color-grey-500);
        place-self: flex-end;
        padding-bottom: var(--spacing-xs);
        text-align: center;

        @include custom-break(1200px) {
          position: absolute;
          right: 55px;
          bottom: 25px;
        }
      }
    }
  }
}
</style>
