import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { CrmCustomerService } from '@domain/crm';
import { DomainOmsService } from '@domain/oms';
import { CustomerDTO } from '@swagger/crm';
import { HistoryDTO as CrmHistoryDTO } from '@swagger/crm';
import { HistoryDTO as OmsHistoryDTO, OrderDTO } from '@swagger/oms';
import { OrderItemListItemDTO } from '@swagger/oms';
import { UiModalRef } from '@ui/modal';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Component({
  selector: 'lib-history',
  templateUrl: 'history.component.html',
  styleUrls: ['history.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HistoryComponent implements OnInit {
  historyError$ = new BehaviorSubject<boolean>(false);
  historyEmpty$ = new BehaviorSubject<boolean>(false);
  spinner$ = new BehaviorSubject<boolean>(true);

  history$: Observable<CrmHistoryDTO | OmsHistoryDTO>;

  get customerName() {
    if (this.ref.data.mode === 'customer' || this.ref.data.mode === 'goods') {
      const data = this.ref.data.item as CustomerDTO;
      return [data?.organisation?.name ?? data?.organisation, data?.lastName, data?.firstName].filter((i) => !!i).join(', ');
    }

    if (this.ref.data.mode === 'order') {
      const data = this.ref.data.item as { order: OrderDTO; orderItemSubsetId: number };
      return [data?.order?.buyer?.organisation, data?.order?.buyer?.lastName, data?.order?.buyer?.firstName].filter((i) => !!i).join(', ');
    }

    return '';
  }

  constructor(
    public ref: UiModalRef<
      any,
      { mode: 'goods' | 'customer' | 'order'; item: CustomerDTO | OrderItemListItemDTO | { order: OrderDTO; orderItemSubsetId: number } }
    >,
    private customerService: CrmCustomerService,
    private omsService: DomainOmsService
  ) {}

  ngOnInit() {
    switch (this.ref.data.mode) {
      case 'customer':
        this.history$ = this.customerService.getCustomerHistory((this.ref.data.item as CustomerDTO).id).pipe(
          map((response) => {
            this.spinner$.next(false);
            if ((response.result as any).length === 0) {
              this.historyEmpty$.next(true);
            }
            return response.result;
          }),
          catchError(() => {
            this.historyError$.next(true);
            this.spinner$.next(false);
            return of();
          })
        );
        break;
      case 'goods':
        this.history$ = this.omsService.getHistory((this.ref.data.item as OrderItemListItemDTO).orderItemSubsetId).pipe(
          map((history) => {
            this.spinner$.next(false);
            if ((history as any).length === 0) {
              this.historyEmpty$.next(true);
            }
            return history;
          }),
          catchError(() => {
            this.historyError$.next(true);
            this.spinner$.next(false);
            return of();
          })
        );
        break;
      case 'order':
        this.history$ = this.omsService
          .getHistory((this.ref.data.item as { order: OrderDTO; orderItemSubsetId: number }).orderItemSubsetId)
          .pipe(
            map((history) => {
              this.spinner$.next(false);
              if ((history as any).length === 0) {
                this.historyEmpty$.next(true);
              }
              return history;
            }),
            catchError(() => {
              this.historyError$.next(true);
              this.spinner$.next(false);
              return of();
            })
          );
        break;
    }
  }
}
