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 r: Router,
        private as: ApiService,
        private us: UtilsService
    ) {
    }

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

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