import {Injectable} from '@angular/core';
import {ApiService} from "../../shared/service/api.service";
import {Observable} from "rxjs";
import {Material} from "../../shared/model/material.model";
import {FileInput} from "ngx-material-file-input";

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

  get all(): Observable<Material[]> {
    return this.api.get<Material[]>('/material')
  }

  getAllForMixCreation(recipeId: number): Observable<Material[]> {
    return this.api.get<Material[]>(`/material/mix/create/${recipeId}`)
  }

  getAllForMixUpdate(mixId: number): Observable<Material[]> {
    return this.api.get<Material[]>(`/material/mix/update/${mixId}`)
  }

  getById(id: number): Observable<Material> {
    return this.api.get<Material>(`/material/${id}`)
  }

  hasSimdut(id: number): Observable<boolean> {
    return this.api.get<boolean>(`/material/${id}/simdut/exists`)
  }

  save(name: string, inventoryQuantity: number, materialType: number, simdutFile: FileInput): Observable<void> {
    const body = new FormData()
    body.append('name', name)
    body.append('inventoryQuantity', inventoryQuantity.toString())
    body.append('materialType', materialType.toString())
    if (simdutFile && simdutFile.files) {
      body.append('simdutFile', simdutFile.files[0])
    }
    return this.api.post<void>('/material/', body)
  }

  update(id: number, name: string, inventoryQuantity: number, materialType: number, simdutFile: FileInput): Observable<void> {
    const body = new FormData()
    body.append('id', id.toString())
    body.append('name', name)
    body.append('inventoryQuantity', inventoryQuantity.toString())
    body.append('materialType', materialType.toString())
    if (simdutFile && simdutFile.files) {
      body.append('simdutFile', simdutFile.files[0])
    }
    return this.api.put<void>('/material/', body)
  }

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