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

@Pipe({
  name: 'bookThumbnail',
})
export class BookThumbnailPipe 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.getThumbnailUrl(value, param).pipe(
        first(),
        map((imgUrl: string) => imgUrl)
      );
    } else {
      return of('');
    }
  }
}
