import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';

import { LoginService } from '../services/login.service';

import { LoggedUserData } from '../structures/logged-user-data';

import * as Globals from '../globals';

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

  userData: LoggedUserData | null = null;

  constructor(private loginService: LoginService, private router: Router) {}

  canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    var subscription = this.loginService.userData$.subscribe((data: LoggedUserData | null) => {
      this.userData = data;
    })
    subscription.unsubscribe();
    if(this.userData != null && this.userData.school != null) {
      return this.evaluateFirstResponse(state.url);
    }
    return this.waitForSecondResponse(state.url);
  }

  async evaluateFirstResponse(triedUrl: string): Promise<boolean> {
    // return this.checkRights(triedUrl);
    // this.router.navigate([Globals.pages.notAuthorized.path], { queryParams: { fromUrl: triedUrl }});
    return true;
  }

  async waitForSecondResponse(triedUrl: string): Promise<boolean> {
    var data: LoggedUserData = await this.loginService.getLoggedUserFromServer();// this.http.get<any>(Globals.api.instructorGetData).toPromise();
    if(data.school != null) {
      // return this.checkRights(triedUrl);
      return true;
    }
    this.router.navigate([Globals.pages.notAuthorized.path], { queryParams: { fromUrl: triedUrl }});
    return false;
  }
  
}
