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 '../services/api.service';
import { UserService } from '../services/user.service';
import { UtilsService } from '../services/utils.service';


@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private apiService: ApiService,
        private utilServices: UtilsService,
        private userService: UserService
    ) {

    }
    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> {
        let params = {
            environment: environment.envName,
            queryType: "All"
        }

        return this.apiService.post(`svc/EnvironmentInformation`, params).map(
            (data) => {
                if (this.utilServices.isSuccessfulResponse(data)) {

                    this.userService.setDetailsFromData(data);

                    if (data.UserName == "noprivauthtoken") {
                        let redirectPage = route.data["redirectPage"] || "editor/";

                        window.location.href = (environment.baseUrl + redirectPage + "?url=" + encodeURIComponent(window.location.href));
                        return false;
                    } else {
                        let privs = route.data["privs"] as Array<string>;

                        if (privs) {
                            if (!this.userService.hasPrivilegeFromMultiple(privs)) {
                                this.router.navigate(['access-denied']);
                            }
                        }
                        //localStorage.setItem('userid', data.UserID);
                        return true;
                    }
                }
            }
        )
        .catch(
            (err) => of(false)
        );
    }
}
