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

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

import { InstructorData } from '../structures/instructor-data';
import { LoggedUserData } from '../structures/logged-user-data';
import { emptyInstructorDataFactory } from '../empty-objects/empty-instructor-data';

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

@Injectable({
  providedIn: 'root',
})
export class InstructorGuard 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.instructor != null) {
      return this.evaluateFirstResponse(next.data.minimalAllowed, this.userData.instructor.role, state.url);
    }
    return this.waitForSecondResponse(next.data.minimalAllowed, state.url);
  }

  async evaluateFirstResponse(minimalAllowed: string, actualUser: string, triedUrl: string): Promise<boolean> {
    return this.checkRights(minimalAllowed, actualUser, triedUrl);
  }

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

  checkRights(minimalAllowed: string, actualUser: string, triedUrl: string): boolean {
    var allowedRoles = Globals.instructorRoles.slice(Globals.instructorRoles.indexOf(minimalAllowed));
    if(allowedRoles.indexOf(actualUser) != -1) {
      return true;
    }
    this.router.navigate([Globals.pages.notAuthorized.path], { queryParams: { fromUrl: triedUrl }});
    return false;
  }
}
