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

                            return false;
                        }

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