package io.gmss.fiscad.controllers;

import io.swagger.v3.oas.annotations.tags.Tag;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRSaver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping(value = "api/open", produces = MediaType.APPLICATION_JSON_VALUE)
@Tag(name = "Open")
@CrossOrigin(origins = "*")
public class OpenController {

    @Value("${file.jasper-reports}")
    private String jaspersDir;

    private static final Logger logger = LoggerFactory.getLogger(OpenController.class);

    @GetMapping("/compile-report")
    public ResponseEntity<?> compile(@RequestParam String jrxmlFileName) {
        try {
            InputStream quitusReportStream = getStream(jaspersDir + "/" + jrxmlFileName + ".jrxml");
            JasperReport jasperReport = JasperCompileManager.compileReport(quitusReportStream);
            JRSaver.saveObject(jasperReport, jaspersDir + "/" + jrxmlFileName + ".jasper");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream getStream(String fileName) throws IOException {
        File initialFile = new File(fileName);
        InputStream stream = new FileInputStream(initialFile);
        return stream;
    }


}
