import { Component, ChangeDetectionStrategy } from '@angular/core';
import { BranchDTO } from '@swagger/checkout';
import { first } from 'rxjs/operators';
import { PurchasingOptionsListModalStore } from '../purchasing-options-list-modal.store';

@Component({
  selector: 'page-pick-up-option-list',
  templateUrl: 'pick-up-option-list.component.html',
  styleUrls: ['../list-options.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PickUpOptionListComponent {
  branches$ = this._store.branches$;
  selectedBranch$ = this._store.selectedPickUpBranch$;
  selectedOption$ = this._store.selectedFilterOption$;
  optionChipDisabled$ = this._store.fetchingAvailabilities$;

  constructor(private _store: PurchasingOptionsListModalStore) {}

  optionChange(option: string) {
    if (this._store.selectedFilterOption === option) {
      this._store.selectedFilterOption = undefined;
    } else {
      this._store.selectedFilterOption = option;
    }
  }

  async selectBranch(branch: BranchDTO) {
    this._store.lastSelectedFilterOption$.next(undefined);

    this._store.selectedPickUpBranch = branch;

    const shoppingCartItems = await this._store.shoppingCartItems$.pipe(first()).toPromise();
    shoppingCartItems.forEach((item) => this._store.loadPickUpAvailability({ item }));
  }
}
