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-take-away-option-list',
  templateUrl: 'take-away-option-list.component.html',
  styleUrls: ['../list-options.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TakeAwayOptionListComponent {
  branches$ = this._store.branches$;
  selectedBranch$ = this._store.selectedTakeAwayBranch$;
  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.selectedTakeAwayBranch = branch;

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