import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApplicationService } from '@core/application';
import { CrmCustomerService } from '@domain/crm';
import { BonusCardInfoDTO, CustomerDTO } from '@swagger/crm';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

@Component({
  selector: 'page-customer-card',
  templateUrl: 'customer-card.component.html',
  styleUrls: ['customer-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomerCardComponent implements OnInit {
  customer$: Observable<CustomerDTO>;
  customerId$: Observable<number>;

  customerCard$: Observable<BonusCardInfoDTO>;
  partnerCards$: Observable<BonusCardInfoDTO[]>;

  constructor(
    private route: ActivatedRoute,
    private customerService: CrmCustomerService,
    public readonly applicationService: ApplicationService
  ) {}

  ngOnInit() {
    this.customerId$ = this.route.params.pipe(map((p) => Number(p['customerId'])));

    this.customer$ = this.customerId$.pipe(
      switchMap((id) => this.customerService.getCustomer(id, 2)),
      map((cr) => cr.result)
    );

    this.customerCard$ = this.customerId$.pipe(
      switchMap((id) => this.customerService.getCustomerCard(id)),
      map((response) => response.result?.find((card) => card.isPrimary))
    );

    this.partnerCards$ = this.customerId$.pipe(
      switchMap((id) => this.customerService.getCustomerCard(id)),
      map((response) => response.result?.filter((card) => !card.isPrimary))
    );
  }

  onCancelCard(): void {}
}
