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

@Component({
  selector: 'cre-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.sass']
})
export class NavComponent implements OnInit, OnDestroy {
  private _destroy$ = new Subject<boolean>()

  @Input() links: NavLink [] = []

  // links: NavLink[] = [
  //   {route: 'materialtype', title: 'Types de produit', enabled: true}
  // ]
  _activeLink: string | null;

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

  ngOnInit(): void {
    this.updateEnabledLinks(this.appState.authenticatedEmployee)

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

  ngOnDestroy(): void {
    this._destroy$.next(true)
    this._destroy$.complete()
  }

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

  get activeLink() {
    return this._activeLink
  }

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

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