import {Component, OnDestroy, OnInit, ViewChild, NgModule} from '@angular/core';
import {Router, Routes, RoutesRecognized, ActivatedRoute} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {Authorization} from 'src/app/models/Authorization';
import {User} from 'src/app/models/User';
import {Community} from 'src/app/models/Community';
import { Page } from "src/app/models/Page";
import {AppService} from 'src/app/services/app.service';
import {UserService} from 'src/app/services/user.service';
import {takeWhile} from "rxjs/operators";
import { PageService } from 'src/app/services/page.service';
import { Subscription } from 'rxjs';
import {MessageService} from 'primeng/api';
import { UtilsService } from 'src/app/services/utils.service';

import { Location } from '@angular/common';
import { environment } from 'src/environments/environment';


@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit, OnDestroy {
	title = 'lec';
	
	slug : string = "";
	pages: Page[] = [];
	alive: boolean = true;

	user?: User = new User();
	disposeOnDestroySubscriptions: Subscription[] = [];
	lastLoadedLang: string | null = null;
	isAdmin: boolean = false;
	isManager: boolean = false;
	communities: Community[] = this.user?.usercommunities!;

	selectedCommunity : Number = 0;

	    constructor(
			private route: ActivatedRoute,
	        public translate: TranslateService,
	        public app: AppService,
	        private router: Router,
	        private userService: UserService,
	        private messageService: MessageService,
	        private pageService: PageService, 
			private utils: UtilsService,
			private location: Location
	    ) { }

		login(){
			window.location.href = environment.authenticationUrl;
		}

	    ngOnDestroy() {
	        this.alive = false;
	        for (const subscription of this.disposeOnDestroySubscriptions)
	            subscription.unsubscribe();
	    }

	    ngOnInit(): void {
	        this.disposeOnDestroySubscriptions.push(
	            this.app.onAuthorizationDone()
	                .pipe(takeWhile(() => this.alive))
	                .subscribe((authorization: Authorization) => {
	                if (authorization) {
	                    this.user = authorization.user;
	                    this.app.user = authorization.user!;
	                    //console.info("Header: authorization: ", authorization);
	                }
	        		if(this.user?.usercommunities[0] != null ){
						this.selectedCommunity = this.user?.usercommunities[0].communityid! ? + this.user?.usercommunities[0].communityid! : 0;
					}
					
					
					this.app.community = this.user?.usercommunities[0] ? this.user?.usercommunities[0] : new Community();
	                this.lastLoadedLang = this.app.getLanguage();   
					if (this.user && !this.user.newUser){						
						this.setUserProperties();
	                    this.loadPages();       
					}
					if(this.user?.newUser){
						this.utils.showInfoMessage("New user");
						this.router.navigateByUrl("/update");
					}  
					
	            }),
	            this.translate.onLangChange.subscribe( lang => 
	                {
	                    const langHasChanged = lang.lang !== this.lastLoadedLang;
	                    
	                    if (this.user && langHasChanged){
	                        this.loadPages();
	                    }
	                    this.lastLoadedLang = lang.lang;
	                }
	            )
	        );
	    }

	    loadPages() {
			if(this.user!.name != ''){
			this.pageService.getUserPages().subscribe(pages => { 
	            this.pages = pages; 
	        }); 
			}
	    }

	    initMenu() {        

	        if (!this.pages || this.pages.length === 0)
	            return;

	    }

		setUserProperties(){
			for(let authority of this.user!.authorities!){
				if (authority.authority === 'admin') this.isAdmin = true;
			}

			for(let role of this.user!.userroles!){
				if (this.selectedCommunity === role.communityID && role.roleID === 7) 
					this.isManager = true;
			}

		}

	    private createMenuItemsFromPages(pages: Page[]) {

/*/	        return pages.map(page => <MenuItem>{
	            id: page.slug,
	            label: page.name,
	            routerLink: page.path,
	            styleClass: "menuLevel1",
	            state: { defaultPage: page.defaultPage },
	            command: (event) => {
	                const slug = event?.item?.id as string | undefined;
	                if (slug)
	                    this.app.getPageConfiguration(slug);                
	            }
	        });
*/
		}
	    
	    private createMenuItemsFromLanguages(languages: string[]) {

/*	        return languages.map(language => <MenuItem>{
	            label: language,
	            styleClass : "menuLevel1", 
	            command: () =>  this.setActualLanguage(language)
	        });*/
	    }

	    logout() {
	        this.userService.logout().subscribe(
	            _ => {
	                this.clearUserData();
	            },
	            err => {
	                console.error(err);
	                this.clearUserData();
	            }
	        );
	    }

	    clearUserData() {
	        this.app.removeAuthorization();
	        this.pages = [];
	        this.router.resetConfig(this.router.config.filter(o => !o.data || !o.data.dynamic));
	        this.router.navigateByUrl("/");
			this.user = new User();
			this.isAdmin = false;
			this.isManager = false;
	    }

	    echoUser() {
	        this.userService.getUserFullName();
	    }

	    setActualLanguage(lang: string) {
	        this.app.setLanguage(this.translate, lang);
	    }
	    
	    public goToPage(slug : string){
	    	this.slug = slug;
	    	if (slug)
	            this.app.getPageConfiguration(slug);
	    }
	    
		setCommunity(event: Event){
	  		this.registerParams("communityid", this.app.community.communityid);	
			this.selectedCommunity = + this.app.community!.communityid!;
		}

		registerParams(paramName: string, value?: string){
			let queryParams: any = {};
				queryParams[paramName] = value;
			
				this.router.navigate([], {
				relativeTo: this.route,
				queryParams: queryParams,
				queryParamsHandling: 'merge',
				skipLocationChange: false
			  });
			}

}
