import { Injectable } from '@angular/core';
import { CustomError } from '@msfa-models/error/custom-error';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class ErrorService {
  private _errorQueue$ = new BehaviorSubject<CustomError[]>([]);

  public errors$: Observable<CustomError[]> = this._errorQueue$.pipe(
    map(errors => errors.sort((a, b) => (a.timestamp > b.timestamp ? -1 : 1)))
  );

  public add(error: CustomError): void {
    this._errorQueue$.next([...this._errorQueue$.value, error]);
  }

  public remove(error: CustomError): void {
    const newErrorQueue = this._errorQueue$.value.filter(currentError => currentError.id !== error.id);
    this._errorQueue$.next(newErrorQueue);
  }
}
