import {Component} from '@angular/core';
import {ActivatedRoute, ResolveEnd, Router} from "@angular/router";
import {AppState} from "../../app-state";
import {Employee, EmployeePermission} from "../../model/employee";
import {AccountService} from "../../../accounts/services/account.service";
import {SubscribingComponent} from "../subscribing.component";
import {FormBuilder} from "@angular/forms";

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

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

  ngOnInit(): void {
    // Gets the current route
    this.subscribe(
      this.router.events,
      {
        next: data => {
          if (data instanceof ResolveEnd) this._activeLink = data.url
        }
      },
      1
    )

    // Auth status
    this.accountService.checkAuthenticationStatus()
    this.updateEnabledLinks(this.appState.isAuthenticated, this.appState.authenticatedEmployee)
    this.subscribe(
      this.appState.authenticatedUser$,
      {next: authentication => this.updateEnabledLinks(authentication.authenticated, authentication.authenticatedUser)}
    )

    super.ngOnInit()
  }

  ngOnDestroy(): void {
    this.accountService.logout(() => {
      console.log("Successfully logged out")
    })

    super.ngOnDestroy()
  }

  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?
  ) {
  }
}
