import { Component, ChangeDetectionStrategy } from '@angular/core';
import { DomainAvailabilityService } from '@domain/availability';
import { BranchDTO } from '@swagger/checkout';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PurchasingOptionsModalStore } from '../purchasing-options-modal.store';

@Component({
  selector: 'page-pick-up-option',
  templateUrl: 'pick-up-option.component.html',
  styleUrls: ['../option.scss', 'pick-up-option.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PickUpOptionComponent {
  branches$: Observable<BranchDTO[]> = this._purchasingOptionsModalStore.selectAvailableBranches;
  selected$: Observable<string> = this._purchasingOptionsModalStore.selectBranch.pipe(map((branch) => branch.name));

  readonly item$ = this._purchasingOptionsModalStore.selectItem;

  readonly availability$ = this._purchasingOptionsModalStore.selectAvailabilities.pipe(map((ava) => ava['pick-up']));

  readonly price$ = combineLatest([this.availability$, this.item$]).pipe(
    map(([availability, item]) => this._availabilityService.getPriceForAvailability('pick-up', item.catalogAvailability, availability))
  );

  constructor(private _purchasingOptionsModalStore: PurchasingOptionsModalStore, private _availabilityService: DomainAvailabilityService) {}

  select() {
    this._purchasingOptionsModalStore.setOption('pick-up');
  }

  selectBranch(branch: BranchDTO) {
    this._purchasingOptionsModalStore.setBranch(branch);
  }
}
