import { Injectable } from '@angular/core';
import { CustomError } from '@msfa-models/error/custom-error';
import { mapNewsResponseToNews, News } from '@msfa-models/news.model';
import { NewsApiService } from '@msfa-services/api/news.api.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class StartService {
  private _newsLoading$ = new BehaviorSubject<boolean>(false);
  public newsLoading$: Observable<boolean> = this._newsLoading$.asObservable();

  constructor(private newsApiService: NewsApiService) {}

  public fetchNews$(): Observable<News> {
    this._newsLoading$.next(true);

    return this.newsApiService.fetchNews$().pipe(
      map(response => {
        this._newsLoading$.next(false);
        return mapNewsResponseToNews(response);
      }),
      catchError((error: CustomError) => {
        this._newsLoading$.next(false);
        throw error;
      })
    );
  }
}
