import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { environment } from '../../../environments/environment';
import { ApiService } from '../../oneit/services/api.service';
import { UtilsService } from '../../oneit/services/utils.service';

@Injectable()
export class HomeGuard implements CanActivate {

    constructor(
        private router: Router,
        private apiService: ApiService,
        private utilsService: UtilsService
    ) {
    }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> {
        const params = {
            environment: environment.envName,
            queryType: 'All'
        };
        return this.apiService.post('svc/EnvironmentInformation', params)
            .map(
                data => {
                    if (this.utilsService.isSuccessfulResponse(data)) {
                        if (data.UserName !== 'noprivauthtoken') {
                            return true;
                        }
                        this.router.navigate(['/my-career-web/auth/login']);

                        return false;
                    }
                }
            )
            .catch(
                () => of(false)
            );
    }
}
