
import { Component, OnInit, Injectable, Inject, ApplicationRef, PLATFORM_ID } from '@angular/core'
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { HttpClient }   from '@angular/common/http'
import { Location, isPlatformBrowser } from '@angular/common'
import { CookieService } from 'ng2-cookies'

import { HelperService } from '@k-core/services/svc.helper'
import { CheckFactory } from '@k-services/factories/fac.check';

@Injectable()
export class busGuard implements CanActivate {

    constructor(
        @Inject(PLATFORM_ID) private platformId: Object,
        private _http: HttpClient,
        private _helper: HelperService,
        private _cookie: CookieService,
        private _checkFactory: CheckFactory,
        private router: Router
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if(isPlatformBrowser(this.platformId)) {

            return this._checkFactory.checkLogin(this._cookie.get('kakesession')).toPromise().then((response: any) => {
                    if(response.logged_in)
                        return true
                    else {
                        this.router.navigate(['/404'])
                        return false
                    }
            })

            // if (localStorage.getItem('user-key')) {
            //     // logged in so return true
            //     return true;
            // }

            // // not logged in so redirect to login page with the return url
            // this.router.navigate(['/pressen'], { queryParams: { returnUrl: state.url }});
            // return false;
        }
    }
}