package fyloz.trial.ColorRecipesExplorer.web.controller;

import fyloz.trial.ColorRecipesExplorer.core.io.FileHandler;
import fyloz.trial.ColorRecipesExplorer.model.Material;
import fyloz.trial.ColorRecipesExplorer.services.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import static fyloz.trial.ColorRecipesExplorer.web.PagesPaths.SIMDUT_FILES;

@Controller
public class SIMDUTFilesController {

    private MaterialService materialService;

    @Autowired
    public SIMDUTFilesController(MaterialService materialService) {
        this.materialService = materialService;
    }

    /**
     * Récupère le fichier SIMDUT voulu sous forme PDF.
     * Cette méthode requiert l'identifiant du produit dans l'URL.
     *
     * @param materialID L'identifiant du produit
     * @return Le fichier SIMDUT en PDF.
     */
    @GetMapping(SIMDUT_FILES)
    public ResponseEntity<byte[]> getFile(@PathVariable int materialID) {
        Material material = materialService.getByID(materialID);

        if (material == null) {
            return ResponseEntity.notFound().build();
        }

        HttpHeaders headers = new HttpHeaders();

        FileHandler fileHandler = new FileHandler(String.format("%s_%s", materialID, material.getMaterialCode()), FileHandler.FileContext.SIMDUT, FileHandler.FileExtension.PDF);
        if (!fileHandler.isValid()) {
            return ResponseEntity.notFound().build();
        }

        byte[] fileContent = fileHandler.readFile();
        headers.setContentType(MediaType.APPLICATION_PDF);
        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }
}
