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 PublicGuard 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') {
                            this.r.navigate(['/my-career-web/dashboard']);

                            return false;
                        }

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