import {Component, OnDestroy, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {AppState} from "../../app-state";
import {Employee, EmployeePermission} from "../../model/employee";
import {AccountService} from "../../../accounts/services/account.service";
import {Subject} from "rxjs";
import {takeUntil} from "rxjs/operators";

@Component({
  selector: 'cre-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.sass']
})
export class HeaderComponent implements OnInit, OnDestroy {
  links: HeaderLink[] = [
    // {route: 'color', title: 'Couleurs', enabled: true},
    {route: 'inventory', title: 'Inventaire', enabled: true},
    new HeaderLink('employee', 'Employés', EmployeePermission.VIEW_EMPLOYEE),
    new HeaderLink('group', 'Groupes', EmployeePermission.VIEW_EMPLOYEE_GROUP),
    {route: 'account/login', title: 'Connexion', enabled: true},
    {route: 'account/logout', title: 'Déconnexion', enabled: false},
  ];
  _activeLink = this.links[0].route;

  private destroy$ = new Subject<boolean>()

  constructor(
    private accountService: AccountService,
    private router: Router,
    private appState: AppState
  ) {
  }

  ngOnInit(): void {
    this.accountService.checkAuthenticationStatus()
    this.updateEnabledLinks(this.appState.isAuthenticated, this.appState.authenticatedEmployee)

    this.appState.authenticatedUser$
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: authentication => this.updateEnabledLinks(authentication.authenticated, authentication.authenticatedUser)
      })
  }

  ngOnDestroy(): void {
    this.destroy$.next(true)
    this.destroy$.complete()
    this.accountService.logout(() => {
      console.log("Successfully logged out")
    })
  }

  set activeLink(link: string) {
    this._activeLink = link
    this.router.navigate([link])
  }

  get activeLink() {
    return this._activeLink
  }

  private updateEnabledLinks(authenticated: boolean, employee: Employee) {
    this.link('account/login').enabled = !authenticated
    this.link('account/logout').enabled = authenticated

    this.links.forEach(l => {
      if (l.requiredPermission) {
        l.enabled = employee && employee.permissions.indexOf(l.requiredPermission) >= 0;
      }
    })
  }

  private link(route: string) {
    return this.links.filter(l => l.route === route)[0]
  }
}

class HeaderLink {
  constructor(
    public route: string,
    public title: string,
    public requiredPermission?: EmployeePermission,
    public enabled = false
  ) {
  }
}
