import { Pipe, PipeTransform } from '@angular/core';
import { map, first } from 'rxjs/operators';
import { of, Observable } from 'rxjs';
import { ImageService } from '../core/services/image.service';

@Pipe({
  name: 'bookImageUrl',
})
export class BookImagePipe implements PipeTransform {
  constructor(private imageService: ImageService) {}

  transform(value: string, width?: number, height?: number): Observable<string> {
    if (value != null) {
      // Default
      let param = {
        width: 150,
        height: 150,
      };

      if (width && height) {
        param = {
          width: width,
          height: height,
        };
      }

      return this.imageService.getImageUrl(value, param).pipe(
        first(),
        map((imgUrl: string) => imgUrl)
      );
    } else {
      return of('');
    }
  }
}
