import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
} from '@angular/core';

@Component({
  selector: 'app-paginator',
  templateUrl: './paginator.component.html',
  styleUrls: ['./paginator.component.scss'],
})
export class PaginatorComponent implements OnChanges {
  @Input() page = 1;
  @Input() totalPages = 1;

  @Output() pageChange = new EventEmitter<number>();

  pages: number[] = [];
  maxPages = 5;

  ngOnInit() {
    this.setPages();
  }

  ngOnChanges(): void {
    this.setPages();
  }

  setPages() {
    if (isNaN(this.page) || isNaN(this.totalPages)) return;

    if (this.page < this.maxPages) {
      this.pages = Array.from(
        { length: Math.min(this.maxPages, this.totalPages) },
        (_, i) => i + 1,
      );

      return;
    }

    if (this.page > this.totalPages - this.maxPages) {
      this.pages = Array.from(
        { length: this.maxPages },
        (_, i) => this.totalPages - this.maxPages + i + 1,
      );

      return;
    }

    this.pages = Array.from(
      { length: this.maxPages },
      (_, i) => this.page - 2 + i,
    );
  }

  onPageChange(page: number) {
    if (page === this.page) return;

    this.pageChange.emit(page);
  }

  goBack() {
    if (this.page === 1) return;

    this.pageChange.emit(this.page - 1);
  }

  goForward() {
    if (this.page === this.totalPages) return;

    this.pageChange.emit(this.page + 1);
  }

  isActive(page: number) {
    return page === this.page;
  }
}
