import { Component, OnDestroy, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { NavEntry } from 'ktelizer';
import { ActivatedRouteSnapshot, NavigationEnd, NavigationError, Router } from '@angular/router';

import { AccountService } from 'app/core/auth/account.service';
import { Account } from 'app/core/user/account.model';
import { Subscription } from 'rxjs';

@Component({
    selector: 'jhi-main',
    templateUrl: './main.component.html'
})
export class MainComponent implements OnInit, OnDestroy {
    account: Account | null = null;
    authSubscription?: Subscription;
    loggedInEntries: NavEntry[] = [];

    defaultEntries: NavEntry[] = [
        {
            title: 'Home',
            url: ''
        }

        // ktelizer-needle-navbar
    ];

    navEntries: NavEntry[] = [];

    constructor(
        private accountService: AccountService,
        private titleService: Title,
        private router: Router
    ) {}

    ngOnInit(): void {
        // try to log in automatically
        this.accountService.identity().subscribe();

        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                this.updateTitle();
            }
            if (event instanceof NavigationError && event.error.status === 404) {
                this.router.navigate(['/404']);
            }
        });

        this.authSubscription = this.accountService.getAuthenticationState().subscribe(account => {
            this.account = account;
            this.renderNavi();
        });
    }

    ngOnDestroy(): void {
        if (this.authSubscription) {
            this.authSubscription.unsubscribe();
        }
    }

    private getPageTitle(routeSnapshot: ActivatedRouteSnapshot): string {
        let title: string = routeSnapshot.data && routeSnapshot.data['pageTitle'] ? routeSnapshot.data['pageTitle'] : '';
        if (routeSnapshot.firstChild) {
            title = this.getPageTitle(routeSnapshot.firstChild) || title;
        }
        return title;
    }

    private updateTitle(): void {
        let pageTitle = this.getPageTitle(this.router.routerState.snapshot.root);
        if (!pageTitle) {
            pageTitle = '<% if (enableTranslation) { %>global.title<% } else { %><%= capitalizedBaseName %><% } %>';
        }
        this.titleService.setTitle(pageTitle);
    }

    private checkAccountAndRenderNavi(): void {
        if (this.accountService.isAuthenticated()) {
            this.accountService.identity().subscribe(
                account => {
                    this.account = account;
                    this.renderNavi();
                },
                () => this.renderNavi()
            );
        } else {
            this.renderNavi();
        }
    }

    renderNavi(): void {
        if (this.account) {
            this.navEntries = [...this.defaultEntries, ...this.loggedInEntries];
        } else {
            this.navEntries = this.defaultEntries;
        }
    }
}
