import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { filter, map, switchMap, distinctUntilChanged, tap, shareReplay } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { HistoryStateFacade } from '@shelf-store/history';
import { OrderHistoryStatus } from '@shelf-store/defs';

@Component({
  selector: 'app-shelf-history',
  templateUrl: './shelf-history.component.html',
  styleUrls: ['./shelf-history.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShelfHistoryComponent implements OnInit {
  status$: Observable<OrderHistoryStatus>;
  orderId$: Observable<number>;
  compartmentCode$: Observable<string>;
  orderItemId$: Observable<number>;
  orderItemSubsetId$: Observable<number>;

  constructor(private activatedRoute: ActivatedRoute, private historyStateFacade: HistoryStateFacade) {}

  ngOnInit() {
    this.status$ = this.getStatus();
    this.orderItemSubsetId$ = this.getOrderItemSubsetId$();
    this.orderId$ = this.getOrderId$();
    this.orderItemId$ = this.getOrderItemId$();
    this.compartmentCode$ = this.getCompartmentCode$();
  }

  fetchHistory = (orderItemSubsetId: number) => {
    this.historyStateFacade.fetchHistory(orderItemSubsetId);
  };

  getStatus() {
    return this.getOrderItemSubsetId$().pipe(switchMap((orderItemSubsetId) => this.historyStateFacade.getStatus$(orderItemSubsetId)));
  }

  getOrderId$(): Observable<number> {
    return this.activatedRoute.params.pipe(
      filter((params) => !isNullOrUndefined(params) && !isNullOrUndefined(params.orderId)),
      map((params) => params.orderId)
    );
  }

  getCompartmentCode$(): Observable<string> {
    return this.activatedRoute.params.pipe(
      filter((params) => !isNullOrUndefined(params) && !isNullOrUndefined(params.compartmentCode)),
      map((params) => params.compartmentCode)
    );
  }

  getOrderItemId$(): Observable<number> {
    return this.activatedRoute.params.pipe(
      filter((params) => !isNullOrUndefined(params)),
      map((params) => Number(params.orderItemId))
    );
  }

  getOrderItemSubsetId$(): Observable<number> {
    return this.activatedRoute.params.pipe(
      filter((params) => !isNullOrUndefined(params)),
      map((params) => Number(params.orderItemSubsetId)),
      distinctUntilChanged(),
      tap(this.fetchHistory),
      shareReplay()
    );
  }
}
