import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { Avrop, AvropCompact } from '@msfa-models/avrop.model';
import { Handledare } from '@msfa-models/handledare.model';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';

@Component({
  selector: 'msfa-avrop-list',
  templateUrl: './avrop-list.component.html',
  styleUrls: ['./avrop-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AvropListComponent {
  @Input() availableAvrop: AvropCompact[];
  @Input() paginationMeta: PaginationMeta;
  @Input() selectedAvrop: AvropCompact[];
  @Input() handledare: Handledare;
  @Input() isLocked: boolean;
  @Input() isSubmitted: boolean;
  @Input() handledareConfirmed: boolean;
  @Input() avropLoading: boolean;
  @Output() selectionChanged = new EventEmitter<AvropCompact[]>();
  @Output() paginated = new EventEmitter<number>();

  get avropRows(): AvropCompact[] {
    return this.isLocked ? this.selectedAvrop : this.availableAvrop;
  }
  get isAllSelected(): boolean {
    return this.selectedAvrop?.length === this.availableAvrop?.length;
  }

  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;
  }

  isSelected(avrop: Avrop): boolean {
    return !!this.selectedAvrop?.find(selectedAvrop => selectedAvrop.id === avrop.id);
  }

  toggleAllAvrop(selected: boolean): void {
    if (selected && this.selectedAvrop?.length !== this.availableAvrop?.length) {
      this.selectionChanged.emit(this.availableAvrop);
    } else if (!selected && this.selectedAvrop.length) {
      this.selectionChanged.emit([]);
    }
  }

  toggleSelectedAvrop(avrop: Avrop, selected: boolean): void {
    const avropIsSelected = !!this.selectedAvrop?.find(selectedAvrop => selectedAvrop.id === avrop.id);

    if (selected && !avropIsSelected) {
      this.selectionChanged.emit([...this.selectedAvrop, avrop]);
    } else if (!selected && avropIsSelected) {
      this.selectionChanged.emit(this.selectedAvrop.filter(selectedAvrop => selectedAvrop.id !== avrop.id));
    }
  }

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