import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
import { Observable ,  of } from 'rxjs';
import jwt_decode from 'jwt-decode';
 
// import { CognitoService } from '../AwsService/cognito.service';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
    token:any =[];
    constructor(private router: Router) { this.token = localStorage.getItem('user_token');   }

    // setToken(token: string): void {
    //   localStorage.setItem(this.token, token);
    // }
  
    // getToken(): string | null {
    //   return localStorage.getItem(this.token);
    // }
  
    clearSession(): void {
      localStorage.removeItem(this.token);
    }

    isTokenExpired(): boolean {
      this.token = localStorage.getItem('user_token');
      const token = this.token;
      if (token) {
        const decoded: any = jwt_decode(token);
        const expirationDate = new Date(0);
        expirationDate.setUTCSeconds(decoded.exp);
        // Get the current datetime
        const currentDatetime = new Date();
        const fiveMinutesBeforeExpiration = new Date(expirationDate);
        console.log(currentDatetime);
        console.log(fiveMinutesBeforeExpiration);
        
        
        if (currentDatetime <= fiveMinutesBeforeExpiration) {
          return true;
        } else {
          return false;
        }
      }
      return true;
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if(this.token != '' && this.token != undefined && this.token != null){
            return true
        }else{
            if(this.token != '' && this.token != undefined && this.token != null)
            {
              return true
               
            }
            else
            {
              console.log('exp');
              
              this.clearSession();
              this.router.navigate(['/auth/login'])
              return false;
            }
        }
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  
        const token = localStorage.getItem('user_token'); 
        // console.log(this.isTokenExpired());

        if(this.token != '' && this.token != undefined && this.token != null)
        {
          if (this.isTokenExpired()) {
            return true
          }
          else{
            console.log('exp');
            localStorage.removeItem('token');
            localStorage.clear()
            this.router.navigate(['/auth/login']);
            return false;
          }
        }
        else
        {
            return true;
        }
    }

  logout() {
    localStorage.removeItem('token');
    localStorage.clear();
    this.router.navigate(['/auth/login']);
  }
}