import { Injectable, NgZone } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { IYesNoDialogData } from './interfaces/yes-no-dialog-data';
import { YesNoDialogComponent } from './yes-no-dialog/yes-no-dialog.component';
import { Observable } from 'rxjs';
import { SnackbarWithLinkComponent } from '@shared/ui/snackbar-with-link/snackbar-with-link.component';
import { ConfigService } from '@shared/config/config.service';
import { LanguageService } from '@shared/language/language.service';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  constructor(
    private matSnackBar: MatSnackBar,
    public matDialog: MatDialog,
    private ngZone: NgZone,
    private config: ConfigService,
    private languageService: LanguageService,
  ) {
  }

  get messageDuration() {
    return this.config?.current?.settings?.messageDuration || 5000;
  }

  get messageWithLinkDuration() {
    return this.config?.current?.settings?.messageWithLinkDuration || 7000;
  }

  showMessage(message: string, duration?: number) {
    this.matSnackBar.open(message, 'Close', {duration: duration || this.messageDuration});
  }

  showMessageWithLink(message: string, urlFragment: string, redirectButtonText: string) {
    this.ngZone.run(() => {
      // make sure this is running in Angular zone
      this.matSnackBar.openFromComponent(SnackbarWithLinkComponent, {
        data: {
          message,
          urlFragment,
          redirectButtonText,
        },
        horizontalPosition: 'center',
        verticalPosition: 'bottom',
        duration: this.messageWithLinkDuration,
      });
    });
  }

  confirmDialog(yesNoData: IYesNoDialogData, disableClose=false, closeAllBefore=false): Observable<IYesNoDialogResult> {
    if (closeAllBefore) {
      this.matDialog.closeAll();
    }
    return this.matDialog.open(YesNoDialogComponent, {
      data: yesNoData,
      disableClose,
      direction: this.languageService.langDirection,
      autoFocus: false,
    }).afterClosed();
  }
}
