package com.capgemini.reports.jasper.printers;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

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

    private final String outputFilePath;
    private final String outputFileName;

    /**
     * Builds a CSV 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 JasperCSVPrinter(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();
        JRCsvExporter exporter = new JRCsvExporter();
        exporter.setExporterInput(new SimpleExporterInput(print));
        File destFile = new File(this.outputFilePath, this.outputFileName + ".csv");
        exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile));
        exporter.exportReport();
        LOGGER.info("CSV creation time : {} ms", System.currentTimeMillis() - start);
        return destFile;
    }
}
