import {Component, OnDestroy, OnInit} from '@angular/core';
import {MenuService} from '../service/menu.service';
import {AuthService} from '../service/auth.service';
import {brokerMenuItems, mainMenuItems, peopleMenuItems, userMenuItems} from '../main-menu-items';
import {ApiV1LoginResponse} from '../models/api-v1-login-response';
import {Subscription} from 'rxjs';
import {PeopleModel} from '../models/people.model';


@Component({
  selector: 'app-top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.scss']
})
export class TopBarComponent implements OnInit , OnDestroy {
  login  = false;
  public LoggedInUser: PeopleModel;

  Avatar = './assets/img/logout.png';
  public items: any[] = mainMenuItems;
  private loginSub: Subscription;

  public showMenu = true;
  public opened = false;

  constructor(private menuService: MenuService,
              private authService: AuthService) {
  }

  ngOnInit(): void {
    this.initAndSubLogin();
  }

  public initAndSubLogin(): void{
    this.login = this.authService.loggedIn.login;
    this.LoggedInUser = this.authService.loggedIn.User;

    this.selectMenuShow(this.authService.loggedIn.role);

    this.loginSub = this.authService.loginSuccess.subscribe(
      (rsp: ApiV1LoginResponse) => {
        this.login = rsp.login;
        this.LoggedInUser = this.authService.loggedIn.User;
        this.selectMenuShow(rsp.role);
      }
    );
  }

  private selectMenuShow(role: string): void {
    this.showMenu = true;
    switch ( role ){
      case 'admin':
        this.items = mainMenuItems;
        break;
      case 'broker':
        this.items = brokerMenuItems;
        break;
      case 'user':
        this.items = userMenuItems;
        break;
      case 'people':
        this.items = peopleMenuItems;
        break;

      default:
        this.showMenu = false;
    }

  }

  // check menuItem has fontawesome
  public menuItemHasFontawesome(item: any): boolean {
    return item.hasOwnProperty('fa');
  }

  // menuItem clicked
  public onSelect({ item }): void {
    if (!item.items) {
      this.menuService.itemClicked.emit(item);

      // handle logout
      if (item.text.toLowerCase() === 'logout'){
        this.logout();
      }
    }
  }

  ngOnDestroy(): void {
    this.loginSub.unsubscribe();
  }

  public logout(): void{
    this.opened = true;
  }

  public close(action: string): void {
    this.opened = false;
    if ( action === 'yes') {
      this.authService.logout();
    }
  }

  public loggedInUserAvatar(): string {
    return this.authService.getUrl('avatar/') + this.authService.loggedIn.User.Id;
  }

  public profile(): void {
    this.menuService.showProfile();
}

}
