/* BdfServer - Copyright (c) 2010-2022 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.balayage.engine.runners;

import fr.exemole.bdfserver.tools.balayage.BdfBalayageUtils;
import fr.exemole.bdfserver.tools.balayage.engine.BalayageLog;
import fr.exemole.bdfserver.tools.balayage.engine.BalayageParameters;
import fr.exemole.bdfserver.tools.balayage.engine.EngineUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Predicate;
import net.fichotheque.addenda.Document;
import net.fichotheque.addenda.Version;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.text.ValueResolver;
import net.fichotheque.exportation.balayage.BalayageOutput;


/**
 *
 * @author Vincent Calame
 */
public class DocumentOutputRunner extends AbstractOutputRunner {

    private Predicate<String> extensionPredicate;

    public DocumentOutputRunner(BalayageParameters balayageParameters, int outputIndex, BalayageOutput output, int balayageUnitIndex) {
        super(balayageParameters, outputIndex, output, balayageUnitIndex);
        extensionPredicate = BdfBalayageUtils.getExtensionPredicate(output.getBalayageUnit());
    }

    public void copy(ValueResolver valueResolver, Document document) {
        File directory = rootDirectory;
        String path = EngineUtils.getPath(output, valueResolver);
        if (path != null) {
            directory = new File(directory, path);
        }
        prepareDirectory(directory);
        for (Version version : document.getVersionList()) {
            if (extensionPredicate.test(version.getExtension())) {
                File destination = new File(directory, version.getFileName());
                try (InputStream is = version.getInputStream(); OutputStream os = new FileOutputStream(destination)) {
                    IOUtils.copy(is, os);
                    balayageLog.addFileGeneration(balayageUnitIndex, outputIndex, destination);
                } catch (IOException ioe) {
                    String msg = ioe.getMessage();
                    String message = ioe.getClass().getName();
                    if (msg != null) {
                        message = message + " : " + msg;
                    }
                    balayageLog.addOutputError(balayageUnitIndex, outputIndex, output, BalayageLog.IO_EXCEPTION, destination.getName(), message);
                }
            }
        }
    }

    @Override
    public void dispose() {
        super.dispose();
        extensionPredicate = null;
    }

}
