<template>
  <div align-h="center" v-show="!disabled">
    <b-col cols="12">
      <b-button-group class="pagination justify-content-center">
        <router-link
          :to="previousPage"
          v-if="pages.length !== 0"
          :class="{ active: parseInt($route.params[identify]) === 1 || $route.params[identify] === undefined }"
        >
          <b-button
            :class="{ disabled: parseInt($route.params[identify]) === 1 || $route.params[identify] === undefined }"
            :data-qa="`${dataQaPrefix}-pagination-previous-btn`"
          >
            <span>{{ $t('Common.Paginator.Previous') }}</span>
          </b-button>
        </router-link>
        <!--Todo quickfix for pagination offset need to enhance-->
        <template v-for="(pageObj, index) in pages">
          <router-link
            v-if="
              (index + 1 >= currentPage - 2 && (index - currentPage === 0 || index - currentPage <= 1)) ||
                (currentPage <= 2 && index + 1 <= paginationSize) ||
                (currentPage + 1 == totalPages && index + 1 >= currentPage - 3) ||
                (currentPage == totalPages && index + 1 >= currentPage - 4)
            "
            :key="index"
            :to="pageObj.route"
            :class="{ active: currentPage === pageObj.name }"
          >
            <b-button class="d-none d-md-inline-block" :data-qa="`${dataQaPrefix}-pagination-page${pageObj.name}-btn`">
              {{ pageObj.name }}
            </b-button>
          </router-link>
        </template>
        <router-link
          :to="nextPage"
          v-if="pages.length !== 0"
          :class="{
            active: (isNaN(parseInt($route.params[identify])) ? 1 : parseInt($route.params[identify])) === pages.length,
          }"
        >
          <b-button
            :class="{
              disabled:
                (isNaN(parseInt($route.params[identify])) ? 1 : parseInt($route.params[identify])) === pages.length,
            }"
            :data-qa="`${dataQaPrefix}-pagination-next-btn`"
          >
            <span>{{ $t('Common.Paginator.Next') }}</span>
          </b-button>
        </router-link>
      </b-button-group>
    </b-col>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'PaginationElement',
  props: {
    name: {
      type: String,
      required: true,
    },
    total: {
      type: Number,
      required: true,
    },
    perPage: {
      type: Number,
      required: true,
    },
    page: {
      type: String,
    },
    paginationSize: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    dataQaPrefix: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      path: '',
      routeName: '',
      params: '',
      previous: '',
      next: '',
      currentPage: 1,
      identify: 'page',
      totalPages: 0,
    }
  },
  async 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 = parseInt(this.$route.params[this.identify] || 1)
    this.turnPage({ page: this.currentPage, perPage: this.perPage, name: this.name })
  },
  methods: {
    ...mapActions(['turnPage']),
  },
  computed: {
    ...mapGetters(['getPagination']),
    pages: function() {
      let totalPages = Math.ceil(this.total / this.perPage)
      let pages = []
      for (let i = 1; i <= totalPages; i++) {
        let route = {
          name: this.routeName,
          params: { ...this.params, [this.identify]: i },
          query: { ...this.$route.query },
        }
        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 (parseInt(this.$route.params[this.identify] || 1) !== this.currentPage) {
        this.currentPage = parseInt(this.$route.params[this.identify])
        this.turnPage({
          [this.identify]: parseInt(params[this.identify]),
          perPage: this.perPage,
          name: this.name,
        }).then(() => {
          this.$emit('getData')
        })
      }
    },
    pages(val) {
      this.totalPages = val.length
    },
  },
}
</script>
