import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { Observable, empty, of } from "rxjs";
import { map, catchError, switchMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';

@Injectable()
export class UnavailableGuard implements CanActivate{
    
    constructor(private http: HttpClient, private router: Router) {}
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.http.get<boolean>('/tadis/auth/available').pipe(
            switchMap(
                () => {
                    this.router.navigate(['/']);
                    return of(false); 
                }
            ),
            catchError(
                (errorResponse: HttpErrorResponse) => {
                    if (errorResponse.status === 504 || errorResponse.status === 503)
                        return of(true);
                    else {
                        this.router.navigate(['/']);
                        return of(false);
                    }
                }
            )
        )
    }

}