import { Injectable, PLATFORM_ID, Inject } from '@angular/core'
import { isPlatformBrowser } from '@angular/common'
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'

import { AppHelper } from '@k-settings/app-helper'
import { hasGuard, store } from '@k-settings/app-setup'
import { SharedService } from '@k-services/svc.shared'
import { LocalstorageService } from '@k-core/services/general/storage'

@Injectable()
export class UserGuard implements CanActivate {

    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        public localStorage: LocalstorageService,
        private _shared: SharedService,
        private router: Router
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        if(!!hasGuard) {

            if(isPlatformBrowser(this._platformId)) {

                if(this.localStorage.getItem('user-key')) {
    
                    this._shared.setPageState(true)
    
                    // logged in so return true
                    return true
                }
    
                // not logged in so redirect to login page with the return url
                this._shared.setPageState(false)

                this.router.navigate([AppHelper.login], { queryParams: { returnUrl: state.url }});
                return false
            }
        } else {

            // Skip login if app does not require guard
            this._shared.setPageState(true)
            return true
        }
    }
}