import { Injectable } from '@angular/core';
import { OrderHistory, OrderHistoryStatus } from '../defs';
import { Store } from '@ngrx/store';
import { Dictionary } from '@ngrx/entity';
import { Observable } from 'rxjs';
import * as selectors from './history.selectors';
import * as actions from './history.actions';
import { HistoryDTO } from '@cmf/trade-api';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class HistoryStateFacade {
  get histories$(): Observable<Dictionary<OrderHistory>> {
    return this.getHistories$();
  }

  constructor(private store: Store<any>) {}

  public fetchHistory(orderItemSubsetId: number): void {
    this.store.dispatch(actions.initOrderHistory({ id: orderItemSubsetId }));
  }

  public reloadHistory(orderItemSubsetId: number): void {
    this.store.dispatch(actions.fetchHistory({ id: orderItemSubsetId }));
  }

  public getHistory$(orderItemSubsetId: number): Observable<HistoryDTO[]> {
    return this.store.select(selectors.selectHistory, orderItemSubsetId);
  }

  public getStatus$(orderItemSubsetId: number): Observable<OrderHistoryStatus> {
    return this.store.select(selectors.selectStatus, orderItemSubsetId);
  }

  public hasErrorStatus$(orderItemSubsetId: number): Observable<boolean> {
    return this.getStatus$(orderItemSubsetId).pipe(map((status) => status === OrderHistoryStatus.ERROR));
  }

  private getHistories$(): Observable<Dictionary<OrderHistory>> {
    return this.store.select(selectors.selectHistories);
  }
}
