import { LoginService } from './../services/login/login.service';
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { LoginDataService } from '../services/login/login-data.service';

@Injectable({
  providedIn: 'root',
})
export class LoginGuard implements CanActivate {
  constructor(
    private _loginData: LoginDataService,
    private _router: Router,
    private _loginService: LoginService
  ) {

  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return new Promise((resolve, _) => {
      let hasinfo = this._loginData.isLogin();
      if(hasinfo){
        let token = localStorage.getItem('token');
        if(token == null){
          return resolve(true);
        }else{
          this._loginData.verifyToken(token).then(res => {
            if(res){
              this._router.navigate(['sam/home']);
              return resolve(false);
            }else{
              return resolve(true);
            }
          });
        }
      }else{
        return resolve(true);
      }
    });
  }
}
