import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { SortOrder } from '@msfa-enums/sort-order.enum';
import { DeltagareCompact } from '@msfa-models/deltagare.model';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';
import { Sort } from '@msfa-models/sort.model';

@Component({
  selector: 'msfa-deltagare-list',
  templateUrl: './deltagare-list.component.html',
  styleUrls: ['./deltagare-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareListComponent {
  @Input() deltagare: DeltagareCompact[];
  @Input() paginationMeta: PaginationMeta;
  @Input() sort: Sort<keyof DeltagareCompact>;
  @Output() sorted = new EventEmitter<keyof DeltagareCompact>();
  @Output() paginated = new EventEmitter<number>();

  columnHeaders: { label: string; key: keyof DeltagareCompact }[] = [
    { label: 'Namn', key: 'fullName' },
    {
      label: 'Tjänst',
      key: 'tjanst',
    },
    {
      label: 'Utförande verksamhet',
      key: 'utforandeVerksamhet',
    },
  ];

  orderType = SortOrder;

  get currentPage(): number {
    return this.paginationMeta.page;
  }

  get totalPage(): number {
    return this.paginationMeta?.totalPage;
  }

  get count(): number {
    return this.paginationMeta.count;
  }

  get currentResultStart(): number {
    return (this.currentPage - 1) * this.paginationMeta.limit + 1;
  }

  get currentResultEnd(): number {
    const end = this.currentResultStart + this.paginationMeta.limit - 1;
    return end < this.count ? end : this.count;
  }

  handleSort(key: keyof DeltagareCompact): void {
    this.sorted.emit(key);
  }

  setNewPage(page: number): void {
    this.paginated.emit(page);
  }
}
