import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { TokenStorageService } from './Services/token.service';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  /**
   * Application title.
   */
  title = 'Aktienbot';

  showHeader = false;
  isLoggedIn = false;

  /**
   * Router import to show router-outlet.
   *
   * @param router Router
   */
  constructor(
    private router: Router,
    private tokenStorage: TokenStorageService
  ) {
    //check if it is login or registration page, header should not show there
    this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe((event) => {
        this.showHeader = !(
          (event as NavigationEnd).url === '/login' ||
          (event as NavigationEnd).url === '/register'
        );

        //check if token already exists from past login
        if (this.tokenStorage.getToken()) {
          this.isLoggedIn = true;
        } else {
          this.isLoggedIn = false;
        }

        //prevent user from accessing dashboard if not logged in
        if (
          this.isLoggedIn === false &&
          (event as NavigationEnd).url != '/register'
        ) {
          this.router.navigate(['/login']);
        }
      });
  }
}
