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> {
        const params = {
            environment: environment.envName,
            queryType: 'All'
        };

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

                        let redirectPage = route.data.redirectPage || 'editor/';
                        this.userService.setDetailsFromData(data);
                        if (data.UserName === 'noprivauthtoken') {
                            const url = window.location.href;
                            const matches = url.match(/job\/(\d+)\/message-engine/);
                            if (matches && matches[1]) {
                                redirectPage = redirectPage.replace(':jobId', matches[1]);
                                window.location.href = `${environment.baseUrl + redirectPage}&from=Messaging`;

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

                            if (privs) {
                                if (!this.userService.hasPrivilegeFromMultiple(privs)) {
                                    this.router.navigate(['access-denied']);
                                }
                            }

                            if (route.routeConfig.path.startsWith('iframe-page') && this.userService.hasPrivilege('TL_AccessAdminPortal')) {
                                this.router.navigate(['/admin/iframe-page', route.params.url]);
                                return;
                            }
                            // localStorage.setItem('userid', data.UserID);

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