import { Component, OnInit, PLATFORM_ID, Inject, Renderer2 }    from '@angular/core'
import { Router, NavigationEnd }  from "@angular/router"

import { AppHelper } from '@k-settings/app-helper'

import { DOCUMENT, isPlatformBrowser, isPlatformServer } from '@angular/common'

import { MenuService }          from '@k-services/svc.menu'
import { BasketService }        from '@k-services/svc.basket'
import { SharedService }        from '@k-services/svc.shared'
import { HelperService }        from '@k-services/svc.helper'


import { routerTransition } from './transition.app'
import { UserService } from '@k-core/modules/User/services/svc.user'
import { cookiebot_Id, hasGuard, server } from '@k-settings/store-helper'
@Component({
	moduleId: module.id+ '', // Adds relative path to assets
	selector: 'app',
	styleUrls: [ 'sty.app.scss' ],
	templateUrl: './tpl.app.pug',
	// animations: [routerTransition],
	providers: [BasketService]
})

export class AppBilkaComponent {
	state: boolean;
	content: boolean = false

	constructor (
		@Inject(PLATFORM_ID) private _platformId,
		@Inject(DOCUMENT) private document,
		private renderer: Renderer2,
		public router: Router,
		private _menuService: MenuService,
		private _sharedService: SharedService,
		private _login: UserService,
		public basketService: BasketService,
		private _helper: HelperService
	) {
		

		if(isPlatformServer(this._platformId) && !!cookiebot_Id) {

			const scriptElt = this.renderer.createElement('script');
			this.renderer.setAttribute(scriptElt, 'type', 'text/javascript');
			this.renderer.setAttribute(scriptElt, 'src', `https://consent.cookiebot.com/${cookiebot_Id}/cc.js?renew=false&referer=${server.split('://')[1]}&dnt=false&forceshow=false&cbid=${cookiebot_Id}&whitelabel=false&brandid=Cookiebot&framework=`);
			this.renderer.appendChild(this.document.head, scriptElt);
		}
		
		/**
		 * Get template load state
		 */
		_sharedService.pageState$.subscribe((response) => {
			this.content = response
		})

		/**
		 * Get menu open/close state 
		 */
		_menuService.state$.subscribe((result) => {
			this.state = result;

			/**
			 * Lock html page height so you cannot scroll when menu is open
			 */
			if(isPlatformBrowser) {
				if(result) {
					this._helper.addClass(document.querySelector('html'), 'is-locked')
				}
				else {
					this._helper.removeClass(document.querySelector('html'), 'is-locked')
				}
			}
		})
		

		_login.checkUser$.subscribe((state: boolean) => {

			if(!state) {
				this._login.logout()
			}
		})
	}

	ngOnInit() {

		if(hasGuard) {
			this._login.checkLogin()
		} else {
			this.content = true
		}

		// If we want to log people out we need to make the customer request passthrough
		if(isPlatformBrowser(this._platformId) && hasGuard) {
			setInterval(() => {

				this._login.checkLogin()
			}, 60000)
		}
	}

	/**
	 * Gets a state?
	 * 
	 * @param outlet
	 */
	getState(outlet) {
		return outlet.activatedRouteData.state
	}
}
