import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import {MatSnackBar} from '@angular/material/snack-bar';

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 NotLoggedGuard implements CanActivate {

  userData: InstructorData = emptyInstructorDataFactory();

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

  canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return this.waitForResponse(next.data.minimalAllowed, state.url);
  }

  async waitForResponse(minimalAllowed: string, triedUrl: string): Promise<boolean> {
    var data: LoggedUserData = await this.loginService.getLoggedUserFromServer();// this.http.get<any>(Globals.api.instructorGetData).toPromise();
    return this.checkRights(minimalAllowed, data, triedUrl);
  }

  async checkRights(minimalAllowed: string, actualUser: LoggedUserData, triedUrl: string): Promise<boolean> {
    if(actualUser.instructor != null) {
      var target = Globals.getAfterLoginPage('instructor', actualUser.instructor.role);
    } else if(actualUser.school != null) {
      var target = Globals.getAfterLoginPage('school', '');
    } else {
      return true;
    }
    this.snackBar.open('V aplikaci jste již přihlášen. Proto došlo k automatickému přesměrování.', 'x', {duration: Globals.snackbarInfoTime, panelClass:'snackBarInfo'});
    this.router.navigate([target.path]);
    return true;
  }
  
}
