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

import { Router } from '@angular/router';

import { TranslateDirective, TranslateService } from '@ngx-translate/core';

import { Subscription } from 'rxjs/Subscription';

import { HeaderService, IMenuItem, IUserAccounts, LoaderService, 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;
    private loaderSubscription: Subscription;

    constructor(private headerService: HeaderService,
        private tokenService: TokenService,
        private userService: UserService,
        private loaderService: LoaderService,
        private router: Router) {
            this.loaderSubscription = this.loaderService.subscribeLoader(this);
        }
    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;
            });
        }
        this.loaderSubscription.unsubscribe();
        this.loaderService.loaderComplete.subscribe((isLoaded: boolean) => {
            if (isLoaded) {
                this.menuItems.forEach((value: IMenuItem) => {
                    value.isActive = this.router.routerState.snapshot.url.indexOf(value.rout) !== -1;
                });
            }
        });
    }
    ngOnDestroy(): void {
        if (this.authorizationChangedSubscription) { this.authorizationChangedSubscription.unsubscribe(); }
        this.loaderSubscription.unsubscribe();
    }
    openSideNav(): void {
        this.sidePanelAction.emit();
    }

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

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