import { Injectable } from '@angular/core';
import { SearchService } from '@swagger/cat';
import { map, catchError } from 'rxjs/operators';
import { of, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ImageService {
  constructor(private catService: SearchService) {}

  getImageUrlFromBackend(ean: string, size: { width: number; height: number } = { width: 150, height: 150 }): Observable<string> {
    return this.catService.SearchSettings().pipe(
      map((response) => {
        sessionStorage.setItem('ImageUrlTemplate', response.result.imageUrl);
        return response.result.imageUrl;
      }),
      map((url) => url.replace('{ean}', ean)),
      map((url) => url.replace('150x150', `${size.width}x${size.height}`)),
      catchError(() => of(''))
    );
  }

  getThumbnailUrlFromBackend(ean: string, size: { width: number; height: number } = { width: 150, height: 150 }): Observable<string> {
    return this.catService.SearchSettings().pipe(
      map((response) => {
        sessionStorage.setItem('ThumbnailUrlTemplate', response.result.thumbnailImageUrl);
        return response.result.thumbnailImageUrl;
      }),
      map((url) => url.replace('{ean}', ean)),
      map((url) => url.replace('150x150', `${size.width}x${size.height}`)),
      catchError(() => of(''))
    );
  }

  getImageUrl(ean: string, size: { width: number; height: number } = { width: 150, height: 150 }): Observable<string> {
    const imageUrlTemplate = sessionStorage.getItem('ImageUrlTemplate');
    if (imageUrlTemplate) {
      return of(imageUrlTemplate).pipe(
        map((url) => url.replace('{ean}', ean)),
        map((url) => url.replace('150x150', `${size.width}x${size.height}`)),
        catchError(() => of(''))
      );
    }
    return this.getImageUrlFromBackend(ean, size);
  }

  getThumbnailUrl(ean: string, size: { width: number; height: number } = { width: 150, height: 150 }): Observable<string> {
    const thumbnailUrlTemplate = sessionStorage.getItem('ThumbnailUrlTemplate');
    if (thumbnailUrlTemplate) {
      return of(thumbnailUrlTemplate).pipe(
        map((url) => url.replace('{ean}', ean)),
        map((url) => url.replace('150x150', `${size.width}x${size.height}`)),
        catchError(() => of(''))
      );
    }
    return this.getThumbnailUrlFromBackend(ean, size);
  }
}
