import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { lastValueFrom, Observable } from 'rxjs';
import { IAMService } from '../services/iam/iam.service';
import { TokenService } from '../services/token/token.service';

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

  constructor(private _tokenService: TokenService, private iamService: IAMService){}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {      
      return new Promise((resolve) => {
        this.checkToken().then(
          (data:boolean)=> resolve(data)
        );
      });
      /* eturn new Promise((resolve) => {
        lastValueFrom(this._tokenService.checkToken()).then(
          () => resolve(true),
          (error: any) => {
            console.log(error);
            if(error.status === 409){
              this.iamService.logout();
              window.location.href = "https://qasirh.ittec.mx/";
            }
          }
        )
      }); */
  }

  async checkToken(){
    try{
      await lastValueFrom(this._tokenService.checkToken());
      return true;
    }catch(error:any){
      this.iamService.logout();
      window.location.href = "https://qasirh.ittec.mx/";
      return false;
    }
  }
}
