import { Injectable, OnInit } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable, ReplaySubject, throwError, map, of } from 'rxjs'; import { catchError, switchMap, tap } from 'rxjs/operators'; import { Entry } from '../../shared/models/entry.model'; import { EntryId } from '../../shared/models/entryId.model'; import { EntryRating } from '../../shared/models/entryRating.model'; // import { environment } from '../../../environments/environment'; @Injectable({ providedIn: 'root', }) export class LibraryService implements OnInit { // libraryEntries: Entry[] = []; private libraryEntriesSubject = new ReplaySubject(1); private entriesLoaded = false; // Flag to track if the entries have been loaded private backend_apiUrl = ' http://localhost:4000/api/v1'; constructor(private http: HttpClient) {} ngOnInit() { this.fetchAllEntries(true); } public getAllEntries(forceFetch: boolean = false): Observable { if (this.entriesLoaded && !forceFetch) { return this.libraryEntriesSubject.asObservable(); } else { // Note: This now properly chains the observable without directly subscribing here. return this.fetchAllEntries(forceFetch); } } // public refreshEntries(forceFetch: boolean = true): Observable { // return this.getAllEntries(forceFetch); // } // private apiUrl = environment.apiBaseUrl; /** * Fetches data from the specified endpoint and returns an Observable. * @param {string} endPoint The URL of the API endpoint to fetch data from. * @param {Object} params Optional query parameters to append to the request URL. * @returns {Observable} An Observable that emits the fetched data. */ fetchData( endPoint: string, params?: { [param: string]: string | number } ): Observable { // Initialize HttpParams from the provided params object let httpParams = new HttpParams(); if (params) { Object.keys(params).forEach((key) => { httpParams = httpParams.set(key, params[key]); }); } return this.http.get<{ results: any[] }>(endPoint, { params: httpParams }); } private fetchAllEntries(forceFetch: boolean = false): Observable { const endPoint = `${this.backend_apiUrl}/entries`; // If data is already loaded and not force fetching, immediately return the cached observable. if (this.entriesLoaded && !forceFetch) { return this.libraryEntriesSubject.asObservable(); } else { // Data needs to be (re)fetched. return this.fetchData(endPoint).pipe( tap((entries) => { // Cache the latest entries and mark as loaded. entries.forEach((entry: Entry) => (entry.isInLibrary = true)); this.libraryEntriesSubject.next(entries); this.entriesLoaded = true; }), catchError((error) => { // Log and rethrow the error for the caller to handle. console.error('Failed to fetch entries:', error); this.entriesLoaded = false; // Allow for a retry on subsequent calls. return throwError(() => new Error('Failed to fetch entries')); }) ); } } // /** // * Fetches library data with page and pagesize and returns an Observable. // * @param {string} endPoint The URL of the API endpoint to fetch data from. // * @param {Object} params Optional query parameters to append to the request URL. // * @returns {Observable} An Observable that emits the fetched data. // */ // getEntries(page: number, pageSize: number): Observable { // var endPoint = `${this.backend_apiUrl}/entries`; // return this.fetchData(endPoint, { page: page, pageSize: pageSize }).pipe( // map((response) => // response.results.map((movie: any) => this.mapMovieToEntry(movie)) // ) // ); // } // /** // * Retrieves a specific page of entries from the library. // * // * @param page The page number to retrieve. // * @param pageSize Defines the number of entries on each page. // * @returns An Observable emitting the requested page of entries. // */ // getEntriesUsingEndPoint(endPoint: string): Observable { // return this.fetchData(endPoint).pipe( // map((response) => // response.results.map((movie: any) => this.mapMovieToEntry(movie)) // ) // ); // } addEntry(tmdb_id: string, is_tvserie: boolean): Observable { return this.getAllEntries().pipe( switchMap((entries) => { const existingEntry = entries.find((entry) => { if (entry.entryId?.tmdb_id) entry.entryId.tmdb_id == tmdb_id; }); if (existingEntry) { return of(existingEntry); } else { return this.http.post(`${this.backend_apiUrl}/entries`, { tmdb_id: tmdb_id, is_tvserie: is_tvserie, }); } }) ); } deleteEntry(id: number): Observable { // Directly attempt to delete the entry without fetching all entries first. return this.http.delete(`${this.backend_apiUrl}/entries/${id}`); } isInLibrary(tmdb_id: string): Observable { return this.getAllEntries().pipe( switchMap((entries) => { if (entries.length == 0) return of(null); const existingEntry = entries.find((entry) => { // console.log(entry.entryId.tmdb_id, tmdb_id); return entry.entryId.tmdb_id == tmdb_id; }); if (existingEntry) { return of(existingEntry); } else { return of(null); } }) ); } private mapMovieToEntry(movie: any): Entry { const entryId = { tmdb_id: movie.entryId.tmdb_id, } as EntryId; const entryRating = { tmdb_rating: movie.entryRating.tmdb_rating, } as EntryRating; var is_tvseries = movie.release_date == null ? true : false; var release_date = movie.release_date || movie.first_air_date; return { entryId: entryId, entryRating: entryRating, title: movie.title, original_title: movie.original_title, release_date: release_date, storyline: movie.storyline, watchlist: movie.storyline, favorit: false, hidden: false, is_tvseries: is_tvseries, status: movie.status, poster_path: movie.poster_path, } as Entry; } }