<template>
  <b-button size="md" variant="outline-primary" :to="nextPage">
    {{ $t('Enrolment.Paginator.LoadMore.Button') }}
  </b-button>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'SimplePaginationElement',
  props: ['name', 'total', 'perPage', 'page', 'identifier'],
  data() {
    return {
      path: '',
      routeName: '',
      params: '',
      previous: '',
      next: '',
      currentPage: 1,
      identify: 'page',
    }
  },
  mounted() {
    let routeLocation = this.$router.resolve(window.location).route.matched.pop()
    this.path = routeLocation.path
    this.routeName = routeLocation.name
    this.params = routeLocation.params
    // add route pagination path if not specified in the current route
    this.identify = this.$route.params.identifier || 'page'
    let regex = new RegExp(':' + this.identify)
    if (!regex.test(this.path)) {
      this.path += '/:' + this.identify
      this.routeName += 'Paginated'
    }
    this.currentPage = this.$route.params[this.identify] || 1
    let routerPage = this.getPagination(this.name)
    if (typeof routerPage === 'undefined' || routerPage[this.identify] !== this.currentPage) {
      this.turnPage({ page: this.$route.params[this.identify] || 1, perPage: this.perPage, name: this.name })
    }
  },
  methods: {
    ...mapActions(['turnPage']),
  },
  computed: {
    ...mapGetters(['getPagination']),
    pages: function() {
      let totalPages = Math.floor(this.total / this.perPage)
      let pages = []
      for (var i = 1; i <= totalPages; i++) {
        let route = {
          name: this.routeName,
          params: { ...this.params, [this.identify]: i },
        }
        let page = {
          name: i,
          route: route,
        }
        pages.push(page)
      }
      return pages
    },
    previousPage: function() {
      if (parseInt(this.currentPage) - 1 !== 0) {
        return {
          name: this.routeName,
          params: { ...this.params, [this.identify]: parseInt(this.currentPage) - 1 },
        }
      } else {
        return {
          name: this.routeName,
          params: { ...this.params, [this.identify]: parseInt(this.currentPage) },
        }
      }
    },
    nextPage: function() {
      if (parseInt(this.currentPage) !== this.pages.length) {
        return {
          name: this.routeName,
          params: { ...this.params, [this.identify]: parseInt(this.currentPage) + 1 },
        }
      } else {
        return {
          name: this.routeName,
          params: { ...this.params, [this.identify]: parseInt(this.currentPage) },
        }
      }
    },
  },
  watch: {
    '$route.params': function(params) {
      if (this.$route.params[this.identify] !== this.currentPage) {
        this.currentPage = this.$route.params[this.identify]
        this.turnPage({ [this.identify]: params[this.identify], perPage: this.perPage, name: this.name })
      }
    },
  },
}
</script>
