import { inject, Injectable, signal } from "@angular/core";
import { ErrorService } from "../../../shared/error.service";
import { HttpClient } from "@angular/common/http";
import { MediaFile } from "./media-file.model";
import { catchError, map, throwError } from "rxjs";

@Injectable({
    providedIn: 'root',
})
export class MediaFileService {
    private errorService = inject(ErrorService);
    private httpClient = inject(HttpClient);
    private files = signal<MediaFile[]>([]);

    loadedFiles = this.files.asReadonly();

    loadFiles() {
        return this.fetchMediaFiles('http://127.0.0.1:8800/api/media/files', 'Someting went wrong fetching artists. Please try again later-');
    }

    private fetchMediaFiles(url: string, errorMessage: string) {
    return this.httpClient.get<MediaFile[]>(url).pipe(
           map((resData) => resData),
           catchError((error) => {
             console.log(error);
             return throwError(() => new Error(errorMessage));
           })
         );        
    }
}
