import { MatSnackBar } from '@angular/material/snack-bar';
import { SocketService } from './../services/socket.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 AuthGuard implements CanActivate {
  constructor(
    private _loginData: LoginDataService,
    private _router: Router,
    private _socketService: SocketService,
    private _snackBar: MatSnackBar
  ) {

  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return new Promise((resolve, reject) => {
      let hasinfo = this._loginData.isLogin();

      if (!hasinfo) {
        this._loginData.logout();
        this._router.navigate(['login']);
        return resolve(false);
      } else {
        let token = localStorage.getItem('token');
        this._loginData.verifyToken(token!).then(res => {
          if (res) {
            this._socketService.register();
            return resolve(true);
          } else {
            this._snackBar.open('Token expirado.', undefined, {
              duration: 5000
            })
            this._loginData.logout();
            this._router.navigate(['login']);
            return resolve(false);
          }
        })
      }
    });
  }
}
