import {
  Component,
  ChangeDetectionStrategy,
  ContentChildren,
  QueryList,
  AfterContentInit,
  OnDestroy,
  ChangeDetectorRef,
} from '@angular/core';
import { OrderItemListItemDTO } from '@swagger/oms';
import { combineLatest, Observable, Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { GoodsInOutOrderGroupItemComponent } from './goods-in-out-order-group-item.component';

@Component({
  selector: 'shared-goods-in-out-order-group',
  templateUrl: 'goods-in-out-order-group.component.html',
  styleUrls: ['goods-in-out-order-group.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GoodsInOutOrderGroupComponent implements AfterContentInit, OnDestroy {
  @ContentChildren(GoodsInOutOrderGroupItemComponent)
  itemComponents: QueryList<GoodsInOutOrderGroupItemComponent>;

  private _onDestroy$ = new Subject<void>();

  items$: Observable<OrderItemListItemDTO[]>;

  firstItem$: Observable<OrderItemListItemDTO>;

  constructor(private _cdr: ChangeDetectorRef) {}

  ngAfterContentInit() {
    this.registerItemComponentChanges();
  }

  ngOnDestroy() {
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  initObservables() {
    this.items$ = combineLatest(this.itemComponents.map((itemComponent) => itemComponent.item$));
    this.firstItem$ = this.items$.pipe(map((items) => items.find((_) => true)));
  }

  registerItemComponentChanges() {
    this.initObservables();

    this.itemComponents.changes.pipe(takeUntil(this._onDestroy$)).subscribe(() => {
      this.initObservables();
      this._cdr.markForCheck();
    });
  }
}
