<!--
Program: Pagination
Author: SDL
Description: Pagination Common Component
-->
<template>
  <ul class="pagination b-pagination pagination-md justify-content-center">
    <li class="page-item" :class="[{ disabled: currentPage === 1 }]">
      <a href="#" class="page-link" @click.prevent="changePage(1)">≪</a>
    </li>
    <li class="page-item" :class="[{ disabled: currentPage <= 1 }]">
      <a href="#" class="page-link" @click.prevent="changePage(1 >= currentPage - limit ? 1 : currentPage - limit)">
        {{ config.prevText }}
      </a>
    </li>
    <li v-for="num in pages" class="page-item" :class="[{ active: num === currentPage }]" :key="num">
      <a href="#" @click.prevent="changePage(num)" class="page-link">
        {{ num }}
      </a>
    </li>
    <li class="page-item" :class="[{ disabled: currentPage >= lastPage }]">
      <a
        href="#"
        class="page-link"
        @click.prevent="changePage(currentPage > lastPage - limit ? lastPage : currentPage + limit)"
        >{{ config.nextText }}</a
      >
    </li>
    <li class="page-item" :class="[{ disabled: currentPage === lastPage || lastPage === 0 }]">
      <a href="#" class="page-link" @click.prevent="changePage(lastPage)">≫</a>
    </li>
  </ul>
</template>
<script>
export default {
  props: {
    currentPage: {
      required: false,
      type: Number,
    },
    totalRows: {
      required: false,
      type: Number,
    },
    perPage: {
      required: false,
      type: Number,
    },
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      config: { prevText: '<', nextText: '>' },
      curPage: 1,
    };
  },
  created() {
    this.curPage = this.currentPage;
  },
  computed: {
    /**
     * param:
     * return:
     * exception:
     * Description : last page calculation
     */
    lastPage() {
      const total = this.totalRows / this.perPage;
      if (total < 1) return 1;

      if (total % 1 !== 0) return parseInt(total + 1, 10);

      return total;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : page calculation to be shown
     */
    pages() {
      let from = Math.floor((this.currentPage - 1) / this.limit) * this.limit + 1;
      let to = from + (this.limit - 1);
      if (to >= this.lastPage) to = this.lastPage;
      const arr = [];
      while (from <= to) {
        arr.push(from);
        from += 1;
      }
      if (this.totalRows === null) {
        arr.splice(0);
        arr.push(1);
      }
      return arr;
    },
  },
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : Parents' change event call
     */
    changePage(page) {
      this.$emit('change', page);
    },
  },
};
</script>
<style></style>
