import { ChangeDetectionStrategy, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { IconType } from '@msfa-enums/icon-type.enum';
import { DeltagareHandelse, DeltagareHandelseData } from '@msfa-models/deltagare-handelse.model';
import { DeltagareCompact } from '@msfa-models/deltagare.model';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';
import { DeltagareHandelserService } from '@msfa-services/deltagare-handelser.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'msfa-deltagare-list-handelser-dialog',
  templateUrl: './deltagare-list-handelser-dialog.component.html',
  styleUrls: ['./deltagare-list-handelser-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareListHandelserDialogComponent implements OnInit, OnDestroy {
  @Input() deltagare: DeltagareCompact;
  iconType = IconType;
  deltagareHandelserData$: Observable<DeltagareHandelseData>;

  constructor(private deltagareHandelserService: DeltagareHandelserService) {}

  ngOnDestroy(): void {
    this.deltagareHandelserService.resetParams();
  }

  ngOnInit(): void {
    if (this.deltagare) {
      this.deltagareHandelserService.setGenomforandeReferens$(this.deltagare.genomforandeReferens);
      this.deltagareHandelserData$ = this.deltagareHandelserService.deltagareHandelserData$;
    }
  }

  getHandelseDate(handelse: DeltagareHandelse, handelseDate?: string): Date {
    return handelseDate === 'receivedDate' ? new Date(handelse.receivedDate) : new Date(handelse.effectDate);
  }

  currentResultStart(paginationMeta: PaginationMeta): number {
    return (paginationMeta?.page - 1) * paginationMeta?.limit + 1;
  }

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

  setNewPage(page: number): void {
    this.deltagareHandelserService.setPage(page);
  }
}
