package com.capgemini.reports.jasper.compilers;

import com.capgemini.reports.jasper.fillers.MultiFiller;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * This class is able to compile some template files (.jrxml) into a {@link JasperReport} object.
 */
public final class JasperCompiler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MultiFiller.class);

    private static final String JASPER_COMPILATION = "JASPER compilation";
    private static final String JASPER_REPORT_COMPILING_TIME_XXX_MS = "JASPER report Compiling time : {} ms";
    private static final String EXCEPTION_CAUGHT = "Jasper Report Exception caught while compiling report";

    private JasperCompiler() {

    }

    /**
     * Builds a report printer with the provided {@link InputStream} template.
     *
     * @param templateStream the template file to use for this report as an {@link InputStream}
     * @return the compiled {@link JasperReport} object
     * @throws JRException if Jasper could not compile the report
     */
    public static JasperReport compile(final InputStream templateStream) throws JRException {
        LOGGER.debug(JASPER_COMPILATION);
        long start = System.currentTimeMillis();

        try {
            JasperReport compiledReport = JasperCompileManager.compileReport(templateStream);
            LOGGER.debug(JASPER_REPORT_COMPILING_TIME_XXX_MS, System.currentTimeMillis() - start);
            return compiledReport;
        } catch (JRException e) {
            LOGGER.error(EXCEPTION_CAUGHT, e);
            throw e;
        }
    }

    /**
     * Builds a report printer with the provided {@link String} template.
     *
     * @param generatedTemplate the template file to use for this report in a {@link String}
     * @return the compiled {@link JasperReport} object
     * @throws JRException if Jasper could not compile the report
     */
    public static JasperReport compile(final String generatedTemplate) throws JRException {
        LOGGER.debug(JASPER_COMPILATION);
        long start = System.currentTimeMillis();

        try {
            InputStream templateStream = new ByteArrayInputStream(generatedTemplate.getBytes());
            JasperReport compiledReport = JasperCompileManager.compileReport(templateStream);
            LOGGER.debug(JASPER_REPORT_COMPILING_TIME_XXX_MS, System.currentTimeMillis() - start);
            return compiledReport;
        } catch (JRException e) {
            LOGGER.error(EXCEPTION_CAUGHT, e);
            throw e;
        }
    }
}
