import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { DataService as TemplateDataService } from './../pxe/data.service';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  baseUrl: string = this.configService.apiUrl;
  private apiUrl = `${this.baseUrl}/pxe-boot-files?page=1&itemsPerPage=1000`;

  constructor(
    private http: HttpClient,
    private templateDataService: TemplateDataService
  ) {}

  getPxeBootFiles(filters: { [key: string]: string }): Observable<any[]> {
    const params = new HttpParams({ fromObject: filters });

    return this.http.get<any>(this.apiUrl, { params }).pipe(
      map(response => {
        if (response['hydra:member'] && Array.isArray(response['hydra:member'])) {
          return response['hydra:member'];
        } else {
          throw new Error('Unexpected response format');
        }
      }),
      catchError(error => {
        console.error('Error fetching images', error);
        return throwError(error);
      })
    );
  }

  getPxeTemplateOptions(): Observable<any[]> {
    return this.templateDataService.getPxeTemplates({});
  }
}
