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

@Injectable({
  providedIn: 'root'
})
export class GroupService {
  constructor(
    private api: ApiService
  ) {
  }

  get all(): Observable<EmployeeGroup[]> {
    return this.api.get<EmployeeGroup[]>('/employee/group')
  }

  get(id: number): Observable<EmployeeGroup> {
    return this.api.get<EmployeeGroup>(`/employee/group/${id}`);
  }

  get defaultGroup(): Observable<EmployeeGroup> {
    return this.api.get<EmployeeGroup>('/employee/group/default')
  }

  setDefaultGroup(value: EmployeeGroup): Observable<void> {
    return this.api.post<void>(`/employee/group/default/${value.id}`, {})
  }

  getEmployeesForGroup(id: number): Observable<Employee[]> {
    return this.api.get<Employee[]>(`/employee/group/${id}/employees`)
  }

  addEmployeeToGroup(id: number, employee: Employee): Observable<void> {
    return this.api.put<void>(`/employee/group/${id}/${employee.id}`)
  }

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

  save(name: string, permissions: EmployeePermission[]): Observable<EmployeeGroup> {
    const group = {name, permissions}
    return this.api.post<EmployeeGroup>('/employee/group', group)
  }

  update(id: number, name: string, permissions: EmployeePermission[]): Observable<EmployeeGroup> {
    const group = {id, name, permissions}
    return this.api.put<EmployeeGroup>('/employee/group', group)
  }

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