import {Component, OnDestroy, OnInit} from '@angular/core';
import {AppState} from "../../app-state";
import {Employee} from "../../model/employee";
import {Subject} from "rxjs";
import {takeUntil} from "rxjs/operators";

@Component({
  selector: 'cre-employee-info',
  templateUrl: './employee-info.component.html',
  styleUrls: ['./employee-info.component.sass']
})
export class EmployeeInfoComponent implements OnInit, OnDestroy {
  authenticated = false
  employee: Employee = null
  employeeInGroup = false

  private destroy$ = new Subject<boolean>()

  constructor(
    public appState: AppState
  ) {
  }

  ngOnInit(): void {
    this.authenticationState(this.appState.isAuthenticated, this.appState.authenticatedEmployee)
    this.appState.authenticatedUser$
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: authentication => this.authenticationState(authentication.authenticated, authentication.authenticatedUser)
      })
  }

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

  private authenticationState(authenticated: boolean, employee: Employee) {
    this.authenticated = authenticated
    this.employee = employee
    if (this.employee != null) {
      this.employeeInGroup = this.employee.group != null
    }
  }
}
