import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
import { DialogService } from '../services/dialog.service';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { map } from 'rxjs/operators';

export interface ComponentCanDeactivate {
  canDeactivate: (e: any) => boolean | Observable<boolean>;
  forceDeactivate: boolean;
}

@Injectable({
  providedIn: 'root',
})
export class PendingChangesGuard implements CanDeactivate<any> {
  private confirmTitle: string = marker('Unsaved changes');
  private confirmText: string = marker(
    'There are unsaved changes on this page! Are you sure you want to leave?'
  );

  constructor(private dialogService: DialogService) {}

  canDeactivate(component: any): boolean | Observable<boolean> {
    if (!component || component.canDeactivate() || component.forceDeactivate) return true;

    var confirmObservable = this.dialogService
      .openConfirmDialog(this.confirmTitle, this.confirmText)
      .pipe(
        map((confirmed: boolean) => {
          if (confirmed) component.forceDeactivate = true;
          return confirmed;
        })
      );

    return confirmObservable;
  }
}
