import {Component, OnDestroy, OnInit, ViewChild, NgModule} from '@angular/core';
import {Router, Routes, RoutesRecognized} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {Authorization} from 'src/app/models/Authorization';
import {User} from 'src/app/models/User';
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 {MenuItem, MessageService, PrimeIcons} from 'primeng/api';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit, OnDestroy {
    //@ViewChild("menuBar") menuBar?: Menubar;
  	  
    title = 'lec';
    
    items: MenuItem[] = [];
    
    changingLanguage : string = "";
   
    languages : string[] = this.translate.getLangs();
    
    langItems : MenuItem[] = this.createMenuItemsFromLanguages(this.languages);
                  
    pages: Page[] = [];
    alive: boolean = true;

    user?: User;
    disposeOnDestroySubscriptions: Subscription[] = [];
    lastLoadedLang: string | null = null;
    
    constructor(
        public translate: TranslateService,
        public app: AppService,
        private router: Router,
        private userService: UserService,
        private messageService: MessageService,
        private pageService: PageService
    ) { }
    
    ngOnDestroy() {
        this.alive = false;
        for (const subscription of this.disposeOnDestroySubscriptions)
            subscription.unsubscribe();
    }

    ngOnInit(): void {
    	this.initMinimalMenu();
        this.disposeOnDestroySubscriptions.push(
		
            this.app.onAuthorizationDone()
                .pipe(takeWhile(() => this.alive))
                .subscribe((authorization: Authorization) => {
                if (authorization) {
                    this.user = authorization.user;
                    //console.info("Header: authorization: ", authorization);
                }
                if (this.user)
                    this.loadPages();
                this.lastLoadedLang = this.app.getLanguage();            
            }),

            this.translate.onLangChange.subscribe( lang => 
                {
                    const langHasChanged = lang.lang !== this.lastLoadedLang;
                    
                    if (this.user && langHasChanged){
                        this.loadPages();
                    }
                    this.initMinimalMenu();
                    this.lastLoadedLang = lang.lang;
                }
            )
        );
    }

    loadPages() {
        this.pageService.getUserPages().subscribe(pages => { 
            this.pages = pages; 
            this.initMenu();
            this.translateMenuItems();
        }); 
        
    }

    initMinimalMenu(){
    	if (this.user){
    	this.items = [{
    		 icon: 'pi pi-flag',
    		 styleClass: 'menuLevel1', 
    		 style: {'margin-left': 'auto'},
    		 items : this.langItems
    	}, 
    	              {
    		 label: 'LOGIN.SIGN_OUT',
    		 styleClass: 'menuLevel1', 
    		 style: {'margin-left': 'auto'},
    		 icon: 'my-margin-left pi pi-fw pi-sign-out',
    		 command: () => this.logout(), 
    		 routerLink: '/'
    	              }
    	              
    	];
    	}else {
    		this.items = [{
       		 icon: 'pi pi-flag',
       		 styleClass: 'menuLevel1',
       		 items : this.langItems
       	}, 
       	              {
       		 label: 'LOGIN.SIGN_IN',
       		 styleClass: 'menuLevel1', 
       		 style: {'margin-left': 'auto'},
       		  icon: 'my-margin-left pi pi-fw pi-sign-in',
       		 routerLink: '/login'
       	              }
       	              
       	];
    	}
    	this.translateMenuItems();    	 
    }
    
    initMenu() {        
        this.initMinimalMenu();

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

        this.items = [...this.items, ...this.createMenuItemsFromPages(this.pages)];
    }

    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.items = this.items.filter(o => !o.id);
        this.initMenu();
        this.router.navigateByUrl("/login");
    }

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

    setActualLanguage(lang: string) {
        this.app.setLanguage(this.translate, lang);
        this.changingLanguage = lang;
        this.translateMenuItems;
    }
    
    translateMenuItems (){
    	
	this.items.forEach((menuItem: MenuItem) => {
		if (menuItem.label) {
	    	this.translate.get(menuItem.label || "").subscribe((translation: string) => {
	            menuItem.label = translation;
	        });
	    	}
        });
    	
    }
}
