import { CommonModule } from '@angular/common';
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { PurchaseOptionsStore } from '../store';

@Component({
  selector: 'shared-purchase-options-list-header',
  templateUrl: 'purchase-options-list-header.component.html',
  styleUrls: ['purchase-options-list-header.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule],
})
export class PurchaseOptionsListHeaderComponent {
  itemsCount$ = this.store.itemsForList$.pipe(map((items) => items.length));

  selectedItemsCount$ = this.store.selectedItemIds$.pipe(map((ids) => ids.length));

  unselectButton$ = combineLatest([this.itemsCount$, this.selectedItemsCount$]).pipe(
    map(([itemsCount, selectedItemsCount]) => itemsCount === selectedItemsCount),
  );

  selectButton$ = this.unselectButton$.pipe(map((unselectButton) => !unselectButton));

  hideHeader$ = this.store.items$.pipe(map((items) => items?.length === 1));

  constructor(public store: PurchaseOptionsStore) {}

  selectAll() {
    this.store.selectSelectableItems();
  }

  unselectAll() {
    this.store.resetSelectedItems();
  }
}
