import {Injectable, OnDestroy} from '@angular/core';
import {ApiService} from "../../shared/service/api.service";
import {Employee, EmployeePermission} from "../../shared/model/employee";
import {Observable, Subject} from "rxjs";
import {takeUntil} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class EmployeeService implements OnDestroy {
  private _destroy$ = new Subject<boolean>()

  constructor(
    private api: ApiService
  ) {
  }

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

  get all(): Observable<Employee[]> {
    return this.api.get<Employee[]>('/employee', true)
  }

  get(id: number): Observable<Employee> {
    return this.api.get<Employee>(`/employee/${id}`).pipe(takeUntil(this._destroy$))
  }

  save(id: number, firstName: string, lastName: string, password: string, group: number, permissions: EmployeePermission[]): Observable<Employee> {
    const employee = {id, firstName, lastName, password, group, permissions}
    return this.api.post<Employee>('/employee', employee).pipe(takeUntil(this._destroy$))
  }

  update(id: number, firstName: string, lastName: string, permissions: EmployeePermission[]): Observable<void> {
    const employee = {id, firstName, lastName, permissions}
    return this.api.put<void>('/employee', employee).pipe(takeUntil(this._destroy$))
  }

  updatePassword(id: number, password: string): Observable<void> {
    return this.api.put<void>(`/employee/${id}/password`, password, true, {headers: {contentType: 'text/plain'}})
  }

  delete(id: number): Observable<void> {
    return this.api.delete<void>(`/employee/${id}`)
  }
}
