<template>
  <nav class="d-flex justify-content-end" aria-label="Asset overzicht paginatie">
    <p class="d-flex align-items-center mr-2 mb-0">{{ pageRangeLabel }}</p>
    <ul class="pagination m-0">
      <li class="page-item" :class="{disabled: !hasPreviousPage}">
        <button class="page-link" @click="previous" aria-label="Vorige" :disabled="!hasPreviousPage">
          <chevron-left-icon aria-hidden="true" />
        </button>
      </li>
      <li class="page-item" :class="{disabled: !hasNextPage}">
        <button class="page-link" @click="next" :disabled="!hasNextPage" aria-label="Volgende">
          <chevron-right-icon aria-hidden="true" />
        </button>
      </li>
    </ul>
  </nav>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

import { AssetPagination as IAssetPagination } from '../types/api';
import RouteUtils from '../tools/route-utils';

const AssetStore = namespace('assets');

@Component
export default class AssetPagination extends Vue {
  @Prop({ type: Boolean, default: true }) persist!: boolean;

  @AssetStore.State('initialized') readonly initialized!: boolean;
  @AssetStore.State('pagination') readonly pagination!: IAssetPagination;
  @AssetStore.Mutation('setCurrentPage') readonly setCurrentPage!: (currentPage: number) => void;

  mounted() {
    if (this.initialized && !this.$route.query.page) {
      this.setCurrentPage(1);
    }
  }

  previous() {
    this.setCurrentPage(Math.max(0, this.pagination.currentPage - 1));
    this.updateResults();
  }

  next() {
    this.setCurrentPage(this.pagination.currentPage + 1);
    this.updateResults();
  }

  updateResults() {
    if (this.persist) {
      RouteUtils.persistToQuery(this.$router, this.$route, { page: this.pagination.currentPage.toString() });
    }

    this.$emit('update');
  }

  get pageRangeLabel(): string {
    const { currentPage, pageSize, totalResults } = this.pagination;
    const start = (currentPage - 1) * pageSize;
    const end = !this.hasNextPage ? totalResults : start + pageSize;
    const range = totalResults === 0 ? 0 : `${start + 1}-${end}`;

    return `${range} van ${totalResults} assets`;
  }

  get hasPreviousPage(): boolean {
    return this.pagination.currentPage > 1;
  }

  get hasNextPage(): boolean {
    return this.pagination.currentPage < this.pagination.totalPages;
  }
}
</script>
