import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanDeactivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { from, Observable, of } from 'rxjs';
import { DialogService } from '../services/dialog.service';
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { AuthService } from '../server-services/auth.service';
import { flatMap, map, mergeMap, take } from 'rxjs/operators';
import { AccountService } from '../server-services/account.service';
import { MeRecord } from '../server-services/query-records/account-records';


@Injectable({
  providedIn: 'root'
})
export class LogoutPromptGuard implements CanActivate{

  private confirmTitle: string = marker("Logging out");
  private confirmText: string = marker("Are you sure you want to log out?");

  constructor(private dialogService: DialogService, private router: Router, private authService: AuthService){}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
    let mainPromise : Promise<boolean|UrlTree> = new Promise((resolve) => {
      if(this.authService.isAnonym()){
        resolve(this.router.parseUrl('/login'));
      }
      else{
        this.dialogService.openConfirmDialog(this.confirmTitle, this.confirmText).subscribe(confirmed => {
          if(confirmed){
            this.authService.logout().then(() => {
              resolve(this.router.parseUrl('/login'));
            });
          }
          else {
            resolve(false);
          }
        })
      }
    });

    return mainPromise;
  }
  
}
