import { Injectable } from '@angular/core';
import { DomainRemissionService } from '@domain/remission';
import { ComponentStore, tapResponse } from '@ngrx/component-store';
import { ReturnDTO } from '@swagger/remi';
import { Observable, Subject } from 'rxjs';
import { switchMap } from 'rxjs/operators';

export interface RemissionComponentStoreState {
  return?: ReturnDTO;
  returnCount?: number;
}

@Injectable()
export class RemissionComponentStore extends ComponentStore<RemissionComponentStoreState> {
  getReturnCompleted = new Subject<ReturnDTO>();

  get return() {
    return this.get((s) => s.return);
  }

  get return$() {
    return this.select((s) => s.return);
  }

  get returnCount() {
    return this.get((s) => s.returnCount);
  }

  get returnCount$() {
    return this.select((s) => s.returnCount);
  }

  get uncompleted() {
    return this.get((s) => !!s?.return && !s?.return?.completed);
  }

  get uncompleted$() {
    return this.select((s) => !!s?.return && !s?.return?.completed);
  }

  constructor(private readonly _domainRemissionService: DomainRemissionService) {
    super({});
  }

  getReturn = this.effect((returnId$: Observable<number>) =>
    returnId$.pipe(
      switchMap((id) => this._domainRemissionService.getReturn(id)),
      tapResponse(
        (r: ReturnDTO) => {
          this.setReturn(r);
          this.getReturnCompleted.next(r);
        },
        (err) => {
          this.getReturnCompleted.next(undefined);
        }
      )
    )
  );

  getReturns = this.effect((returncompleted$?: Observable<boolean>) =>
    returncompleted$.pipe(
      switchMap((completed) => this._domainRemissionService.getReturns({ returncompleted: completed })),
      tapResponse(
        (r: ReturnDTO[]) => {
          this.setReturnCount(r?.length);
        },
        (err) => {}
      )
    )
  );

  setReturn = this.updater<ReturnDTO>((state, r) => ({
    ...state,
    return: r,
  }));

  setReturnCount = this.updater<number>((state, returnCount) => ({
    ...state,
    returnCount,
  }));
}
