/*
 * Copyright (C) 2017 Robert Bosch GmbH Copyright (C) 2017 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService, MacmaAuthenticationService } from '@bci-web-core/auth';
import { SidebarNavItem } from '@bci-web-core/core';
import { Subject } from 'rxjs';
import { map, startWith, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'bci-auth-app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  sidebarNavigationLinks: SidebarNavItem[] = [
    {
      url: 'home',
      title: 'Home',
      icon: 'Bosch-Ic-home-filled',
    },
    {
      url: 'secured-page',
      title: 'Secured Pages',
      icon: 'Bosch-Ic-lock-closed',
    },
  ];

  sidebarFooterLinks: SidebarNavItem[] = [];
  destroy$: Subject<boolean> = new Subject<boolean>();

  constructor(
    private authenticationService: AuthenticationService,
    private _router: Router,
  ) {  }

  public ngOnInit(): void {
    this.authenticationService
      .isAuthenticated()
      .pipe(
        startWith(false),
        takeUntil(this.destroy$),
        map(
          (isAuthenticated) =>
            <SidebarNavItem[]>[
              {
                title: isAuthenticated ? 'Logout' : 'Login',
                icon: isAuthenticated ? 'Bosch-Ic-user' : 'Bosch-Ic-log-in',
                id: 'sidenav-login-logout',
                cb: () => (isAuthenticated ? this.logout() : this.login()),
              },
            ]
        ),
      )
      .subscribe();
  }

  public ngOnDestroy(): void {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }

  private login() {
    this.authenticationService instanceof MacmaAuthenticationService
      ? (<MacmaAuthenticationService>this.authenticationService).login()
      : this._router.navigate(['/login']);
  }

  private logout() {
    this.authenticationService.logout();
  }
}
