import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

import { Subscription } from 'rxjs/Subscription';

import { HeaderService, IMenuItem, IUserAccounts, TokenService, UserService } from '../../shared';

@Component({
    selector: 'knk-header',
    styleUrls: ['header.component.scss'],
    templateUrl: 'header.component.html'
})
export class HeaderComponent implements OnDestroy, OnInit {
    @Output() sidePanelAction: EventEmitter<boolean> = new EventEmitter<boolean>();

    menuItems: IMenuItem[];
    accounts: IUserAccounts;

    authorizationChangedSubscription: Subscription;
    constructor(private headerService: HeaderService,
        private tokenService: TokenService,
        private userService: UserService,
        private translate: TranslateService) { }
    ngOnInit(): void {
        this.menuItems = this.headerService.getMenu();
        this.authorizationChangedSubscription = this.tokenService.authorizationChanged.subscribe(isLogin => {
            if (isLogin) {
                this.userService.loadUser().subscribe(accounts => {
                    this.accounts = accounts;
                });
            } else {
                this.accounts = null;
            }
        });
        if (this.tokenService.isLogin) {
            this.userService.loadUser().subscribe(accounts => {
                this.accounts = accounts;
            });
        }
    }
    ngOnDestroy(): void {
        if (this.authorizationChangedSubscription) { this.authorizationChangedSubscription.unsubscribe(); }
    }
    setActiveMenu(item: IMenuItem): void {
        this.menuItems.forEach((value: IMenuItem) => value.isActive = false);
        item.isActive = true;
    }
    openSideNav(): void {
        this.sidePanelAction.emit();
    }

    get isLogin(): boolean {
        return this.tokenService.isLogin;
    }

    get lang(): string {
        return this.translate.currentLang;
    }

    public logout(): void {
        console.log('clear');
        this.tokenService.releaseToken();
    }

}
