package com.capgemini.reports.execution.mapconstructor;

import com.capgemini.framework.common.ReportFolderOutputHelper;
import com.capgemini.framework.common.ResourceHelper;
import com.capgemini.reports.exceptions.FileLoadingException;
import com.capgemini.reports.exceptions.ReportPrintException;
import com.capgemini.reports.execution.AbstractExecutionReport;
import com.capgemini.reports.printing.PrintParameters;
import com.capgemini.reports.printing.PrintReportHelper;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;

/**
 * Simple class that will generate a {@link PrintParameters} using a fixed template file.
 *
 * @param <T> the report Type
 * @param <U> the type that holds the relevant report data between the data preparator and the printer
 */
@Slf4j
@EqualsAndHashCode
public abstract class AbstractStaticTemplateMapConstructor<T extends AbstractExecutionReport<T, U>, U> implements IMapConstructor<T, U> {

    private static final long serialVersionUID = 2006289510760058068L;

    @Override
    public PrintParameters makeMasterTemplate(final T report, final U optionalData) throws ReportPrintException, FileLoadingException {
        String storageFolder = ReportFolderOutputHelper.getStorageFolderLocation(report.getLaunchType());
        String fileName = report.getFileNameOnDisc();
        String templateLocation = report.getTemplateLocation();
        try (InputStream templateStream = ResourceHelper.getResourceAsStream(templateLocation)) {
            return PrintReportHelper.setupPrintParameters(templateStream, storageFolder, fileName, report);
        } catch (IOException e) {
            log.error("Unable to close the template file properly from " + templateLocation, e);
            return null; // IOException is only thrown by close() which, if it ever fails, means you have much bigger problems!
        }
    }
}
