import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';
import { WebService } from './web.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private myRoute: Router, public service: WebService) {

  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.auth.isLoggednIn()) {
      const userData = JSON.parse(this.service.getLocalStorageItem('userData'));
      if (next.data.role !== userData.user_type) {
        this.myRoute.navigate(['/404']);
      }
      return true;
    } else {
      this.myRoute.navigate(['/start/login']);
      return false;
    }
  }
}
