<template>
  <div class="sm:flex items-center px-6 py-4">
    <div class="text-center sm:text-left sm:flex-grow">
      <div class="mb-4">
        <p class="flex flex-col sm:flex-row border-b border-2px py-4">
         <span class="flex-1 text-xl font-bold leading-tight ">Recent Projects</span>
         <span class="flex-none text-sm leading-tight text-grey-dark">
           <span @click="changePage(-1)" :class="{'line-through': is_first_page, 'cursor-pointer': !is_first_page}">prev</span>
            /
           <span @click="changePage(1)" :class="{'line-through': is_last_page, 'cursor-pointer': !is_last_page}">next</span>
          </span>
        </p>
      </div>
      <div>
        <!-- {{posts}} -->
        <div v-for="project in posts" v-bind:key="project.id" @click="redirect_href(project.link)" class="flex group cursor-pointer hover:text-white hover:bg-indigo p-4">
            <p class="flex-1 text-lg mb-1 group-hover:text-white " v-html="project.title.rendered"></p>
            <fa-layers full-width class="fa flex-none align-middle ml-2">
              <fa :icon="fas.faArrowCircleRight"/>
            </fa-layers>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { fas } from '@fortawesome/free-solid-svg-icons'

export default {
  mounted() {
    this.fetchPosts()
  },
  methods: {
    async fetchPosts() {
      const posts = await this.$wp.posts().categories(21).perPage(8).page(this.current_page)
      this.posts = posts
      this.total_pages = posts._paging.totalPages
    },
    redirect_href: function (url) {
       window.open(url, '_blank');
    },
    changePage: function (p) {
      var newPage = this.current_page + p
      if (newPage >= 1 && newPage <= this.total_pages) {
        this.current_page = newPage
        this.fetchPosts()
      }
    },
  },
  data () {
    return {
      current_page: 1,
      total_pages: 1,
      posts: [
        {
          id: 0,
          title: {
            rendered: "Loading..."
          }
        }
      ]
    }
  },

  computed: {
    fas () {
        return fas
    },
    is_first_page() {
      return this.current_page == 1
    },
    is_last_page() {
      return this.current_page == this.total_pages
    }
  }
}
</script>
