import { OverlayRef } from '@angular/cdk/overlay';
import { TemplateRef, Type } from '@angular/core';
import { UiModalConfig } from '@ui/modal';
import { Subject } from 'rxjs';
import { UiModalResult } from './modal-result';

export class UiModalRef<TR = any, TD = any> {
  afterClosed$ = new Subject<UiModalResult<TR>>();

  constructor(
    public overlay: OverlayRef,
    public content: TemplateRef<any> | Type<any>,
    public title: string,
    public config: UiModalConfig,
    public data: TD
  ) {}

  _close({ type, data }: { type: 'backdropClick' | 'close'; data: TR }): void {
    this.overlay.dispose();
    this.afterClosed$.next({
      type,
      data,
    });

    this.afterClosed$.complete();
  }

  close(data?: TR): void {
    this._close({ type: 'close', data });
  }
}
