import { Injectable } from '@angular/core';
import { ComponentType } from '@angular/cdk/portal';

import { MatBottomSheet, MatBottomSheetConfig } from '@angular/material';

import { of } from 'rxjs';
import { take, map, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BottomSheetService {
  public constructor(private matBottomSheet: MatBottomSheet) {}

  public open<T, D = any, R = any>(
    componentOrTemplateRef: ComponentType<T>,
    config?: MatBottomSheetConfig<D>
  ): Promise<R> {
    return new Promise<R>((resolve, reject) => {
      const bottomSheetRef = this.matBottomSheet.open<T, D, R>(
        componentOrTemplateRef,
        config
      );

      bottomSheetRef
        .afterDismissed()
        .pipe(
          take(1),
          map(result => {
            return resolve(result);
          }),
          catchError(err => {
            return of(reject(err));
          })
        )
        .subscribe();
    });
  }
}
