import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { DomainOmsService } from '@domain/oms';
import { EntityDTOContainerOfOrderItemDTO, OrderDTO, OrderItemDTO } from '@swagger/oms';
import { combineLatest, Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';

@Component({
  selector: 'page-customer-order-details',
  templateUrl: 'customer-order-details.component.html',
  styleUrls: ['./customer-order-details.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomerOrderDetailsComponent implements OnInit {
  customerId: number;
  orderId: number;
  order$: Observable<OrderDTO>;
  manuallyOrDummyOrderItems$: Observable<EntityDTOContainerOfOrderItemDTO[]>;
  branchName$: Observable<string>;

  constructor(
    private activatedRoute: ActivatedRoute,
    private breadcrumb: BreadcrumbService,
    private application: ApplicationService,
    private orderService: DomainOmsService
  ) {}

  ngOnInit() {
    let params = this.activatedRoute.snapshot.params;
    this.customerId = params['customerId'];
    this.orderId = params['orderId'];

    this.order$ = this.orderService.getOrder(this.orderId).pipe(shareReplay());
    this.branchName$ = combineLatest([this.order$, this.orderService.getBranches()]).pipe(
      map(([order, branches]) => {
        return branches.result.find((b) => b.id === order.targetBranch?.id)?.name;
      })
    );

    this.breadcrumb.addBreadcrumbIfNotExists({
      key: this.application.activatedProcessId,
      name: 'Bestelldetails',
      path: `/kunde/${this.application.activatedProcessId}/customer/${this.customerId}/order/${this.orderId}`,
      tags: ['customer', 'order'],
      section: 'customer',
      params: {},
    });
  }

  hasDummyItems(orderItem: OrderItemDTO): boolean {
    return !!orderItem?.subsetItems?.find((subsetItem) => subsetItem?.data?.supplyChannel === 'MANUALLY');
  }
}
