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

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {
  }

  canActivate(route: ActivatedRouteSnapshot,
              state: RouterStateSnapshot,
  ): boolean | Promise<boolean> | Observable<boolean> {
    if (this.authService.needToRunInit) {
      return this.authService.init().then(result => {
          if (this.authService.isLoggedIn()) {
            return Promise.resolve(true);
          } else if (!this.authService.isLoggedIn()) {
            this.router.navigate(['/auth/passwordSignin']);
            return Promise.reject(false);
          }
        }
      ).catch(reason => {
          this.router.navigate(['/auth/passwordSignin']);
          return Promise.reject(false);
        }
      );
    } else if (this.authService.isLoggedIn()) {
        return Promise.resolve(true);
      } else if (!this.authService.isLoggedIn()) {
        this.router.navigate(['/auth/passwordSignin']);
        return Promise.reject(false);
      }


    }

  }
