import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { map } from 'rxjs';
import { ConfirmationDialogService, ConfirmOptions } from '@iqser/common-ui';

export interface ComponentCanDeactivate {
    changed: boolean;
    valid?: boolean;
    isLeavingPage?: boolean;
    save: () => Promise<void>;
    discard?: () => Promise<void>;
}

@Injectable({ providedIn: 'root' })
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
    constructor(private _dialogService: ConfirmationDialogService) {}

    canDeactivate(component: ComponentCanDeactivate) {
        if (!component.changed) {
            return true;
        }

        component.isLeavingPage = true;

        const dialogRef = this._dialogService.open({ disableConfirm: component.valid === false });
        return dialogRef.afterClosed().pipe(
            map(result => {
                if (result === ConfirmOptions.CONFIRM) {
                    component.save().then();
                } else {
                    component.discard?.().then();
                }
                component.isLeavingPage = false;
                return !!result;
            }),
        );
    }
}
