package com.capgemini.reports.jasper.printers;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Prints a JASPER report to .XLSX.
 */
public class JasperXLSXPrinter implements JasperPrinter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JasperXLSXPrinter.class);

    private final String outputFilePath;
    private final String outputFileName;

    /**
     * Builds a XLSX report printer with the provided parameters.
     *
     * @param outputFilePath the path to the folder where the final output report should be saved
     * @param outputFileName the final output report filename
     */
    public JasperXLSXPrinter(final String outputFilePath, final String outputFileName) {
        this.outputFilePath = outputFilePath;
        this.outputFileName = outputFileName;
    }

    @Override
    public File print(final JasperPrint print) throws JRException {
        long start = System.currentTimeMillis();


        JRXlsxExporter exporter = new JRXlsxExporter();
        exporter.setExporterInput(new SimpleExporterInput(print));
        File destFile = new File(this.outputFilePath, this.outputFileName + ".xlsx");
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));

        SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
        configuration.setRemoveEmptySpaceBetweenRows(true);
        configuration.setRemoveEmptySpaceBetweenColumns(true);

        exporter.setConfiguration(configuration);
        exporter.exportReport();

        LOGGER.info("XLSX creation time : {} ms", System.currentTimeMillis() - start);
        return destFile;
    }

}
