import { Injectable } from '@angular/core';

import { MatPaginatorIntl } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';

const KEY_ITEMS_PER_PAGE = 'common.paginator.itemsPerPage';
const KEY_NEXT_PAGE = 'common.paginator.nextPage';
const KEY_PREV_PAGE = 'common.paginator.prevPage';
const KEY_FIRST_PAGE = 'common.paginator.firstPage';
const KEY_LAST_PAGE = 'common.paginator.lastPage';

@Injectable({
  providedIn: 'root'
})
export class PaginatorIntlService extends MatPaginatorIntl {
  public constructor(private translateService: TranslateService) {
    super();

    this.translateService.onLangChange.subscribe((e: Event) => {
      this.getAndInitTranslations();
    });

    this.getAndInitTranslations();
  }

  public getRangeLabel = (
    page: number,
    pageSize: number,
    length: number
  ): string => {
    if (0 === length || 0 === pageSize) {
      return `0 / ${length}`;
    }

    length = Math.max(length, 0);

    const startIndex = page * pageSize;
    const endIndex =
      startIndex < length
        ? Math.min(startIndex + pageSize, length)
        : startIndex + pageSize;

    return `${startIndex + 1} - ${endIndex} / ${length}`;
    // tslint:disable-next-line: semicolon
  };

  public getAndInitTranslations(): void {
    this.translateService
      .get([
        KEY_ITEMS_PER_PAGE,
        KEY_NEXT_PAGE,
        KEY_PREV_PAGE,
        KEY_FIRST_PAGE,
        KEY_LAST_PAGE
      ])
      .subscribe((translation: any) => {
        this.itemsPerPageLabel = translation[KEY_ITEMS_PER_PAGE];
        this.nextPageLabel = translation[KEY_NEXT_PAGE];
        this.previousPageLabel = translation[KEY_PREV_PAGE];
        this.firstPageLabel = translation[KEY_FIRST_PAGE];
        this.lastPageLabel = translation[KEY_LAST_PAGE];

        this.changes.next();
      });
  }
}
