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

@Component({
  selector: 'page-delivery-option',
  templateUrl: 'delivery-option.component.html',
  styleUrls: ['../option.scss', 'delivery-option.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeliveryOptionComponent {
  readonly item$ = this._purchasingOptionsModalStore.selectItem;

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

  readonly showTooltip$ = combineLatest([this.availability$, this.item$]).pipe(
    map(([availability, item]) => {
      const shippingPrice = availability?.price?.value?.value;
      const catalogPrice = item?.catalogAvailability?.price?.value?.value;
      return catalogPrice < shippingPrice;
    })
  );

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

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

  select() {
    this._purchasingOptionsModalStore.setOption('delivery');
  }
}
