import { RxState } from '@rx-angular/state';
import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';

export type DynamicDialogData<T> = Partial<T> & { dialogComponentName: string };

export function handleDynamicDialog<
  T extends {
    dialogRef: DynamicDialogRef | null;
    dialogConfig: DynamicDialogConfig<DynamicDialogData<TState>> | null;
    state: RxState<TState>;
  },
  TState extends object,
>(this: T) {
  if (
    this.dialogRef &&
    this.dialogConfig &&
    this.dialogConfig?.data?.dialogComponentName === this.constructor.name
  ) {
    this.state.set(this.dialogConfig.data);
  } else {
    this.dialogRef = null;
    this.dialogConfig = null;
  }
}
