import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { BackendService } from '../backend/backend.service';
import { Utilisateur } from '../../models/utilisateur.model';

@Injectable({
	providedIn: 'root'
})
//export class ProfileService implements CanActivate, CanActivateChild {
export class ProfileService implements CanActivate {
	profile:Utilisateur;

	constructor( private bs:BackendService,
				 private router:Router ) { }

	getProfile(): Observable<any> {
		return new Observable((observer) => {
			this.bs.getCurrentUser().subscribe(profile => {
				this.profile = profile;
				observer.next(profile);
				observer.complete()
			}, error => {
				observer.error(error);
				observer.complete();
			})
		});
	}

	canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
		return new Observable((observer) => {
			this.getProfile().subscribe(profile => {
				observer.next(true);
				observer.complete();
			}, error => {
				this.router.navigateByUrl("/login");
				observer.next(false);
				observer.complete();
			})
		});
	}

	//	canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
	//		return new Observable((observer) => {
	//			this.getProfile().subscribe(profile => {
	//				observer.next(true);
	//				observer.complete();
	//			}, error => {
	//				this.router.navigateByUrl("/login");
	//				observer.next(false);
	//				observer.complete();
	//			})
	//		});
	//	}
}
