import { OverlayRef } from '@angular/cdk/overlay';
import { Subject } from 'rxjs';
import { OverlayCloseEvent, ModalContent } from './defs';
import { ModalDialogData } from './modal-dialog-data';

export class IsaModalOverlayRef<T = any> {
  afterClosed$ = new Subject<OverlayCloseEvent<T>>();

  constructor(public overlay: OverlayRef, public content: ModalContent, public data: ModalDialogData<T>) {
    this.overlay.backdropClick().subscribe(() => this.closeModal('backdropClick', null));
  }

  public close(data?: T) {
    this.closeModal('close', data);
  }

  private closeModal(type: OverlayCloseEvent<T>['type'], data: T) {
    this.overlay.dispose();

    this.afterClosed$.next({
      type,
      data,
    });

    this.afterClosed$.complete();
  }
}
