/* BdfServer_Commands - Copyright (c) 2013-2025 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.commands.addenda;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.configuration.ConfigurationUtils;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import net.fichotheque.addenda.Addenda;
import net.fichotheque.tools.parsers.DocumentChangeInfo;
import net.fichotheque.utils.AddendaUtils;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.primitives.FileLength;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.FileName;


/**
 *
 * @author Vincent Calame
 */
public class DocumentFileUploadCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "DocumentFileUpload";
    public final static String FILE_PARAMNAME = "file";
    private Addenda addenda;

    public DocumentFileUploadCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);
    }

    @Override
    public boolean needSynchronisation() {
        return false;
    }

    @Override
    protected void doCommand() throws ErrorMessageException {
        FileValue fileValue = requestHandler.getRequestMap().getFileValue(FILE_PARAMNAME);
        if (fileValue == null) {
            throw BdfErrors.emptyMandatoryParameter(FILE_PARAMNAME);
        }
        if (fileValue.length() < 2) {
            fileValue.free();
            throw BdfErrors.error("_ error.empty.file");
        }
        String originalName = fileValue.getName();
        FileName fileName;
        try {
            fileName = FileName.parse(originalName);
        } catch (ParseException pe) {
            fileName = null;
        }
        if ((fileName == null) || (!AddendaUtils.testExtension(fileName.getExtension().toLowerCase()))) {
            fileValue.free();
            throw BdfErrors.error("_ error.wrong.extension", originalName);
        }
        String basename = AddendaUtils.checkBasename(fileName.getBasename(), addenda);
        String extension = fileName.getExtension().toLowerCase();
        File tmpFile;
        try {
            tmpFile = saveFile(fileValue, extension);
        } catch (IOException ioe) {
            throw BdfErrors.error("_ error.exception.io", ioe.getMessage());
        } finally {
            fileValue.free();
        }
        setDone("_ done.addenda.documentfileupload");
        DocumentChangeInfo documentChangeInfo = DocumentChangeInfo.parse("bn=" + basename + ",tf=" + tmpFile.getName());
        putResultObject(DOCUMENTCHANGEINFO_OBJ, documentChangeInfo);
        putResultObject(STRING_OBJ, fileName.getBasename());
        putResultObject(FILELENGTH_OBJ, new FileLength(tmpFile.length()));
        putResultObject(ADDENDA_OBJ, addenda);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        this.addenda = requestHandler.getMandatoryAddenda();
    }

    private File saveFile(FileValue fileValue, String extension) throws IOException, ErrorMessageException {
        File f = getTmpFile(bdfServer, extension);
        try (InputStream is = fileValue.getInputStream(); OutputStream os = new FileOutputStream(f)) {
            IOUtils.copy(is, os);
        }
        return f;
    }

    public static File getTmpFile(BdfServer bdfServer, String extension) {
        synchronized (bdfServer) {
            File tmpDirectory = ConfigurationUtils.getTmpDirectory(bdfServer, true);
            String number = Long.toHexString(System.currentTimeMillis());
            File f = new File(tmpDirectory, "doc-" + number + "." + extension);
            if (!f.exists()) {
                return f;
            } else {
                int p = 1;
                while (true) {
                    f = new File(tmpDirectory, "doc-" + number + "_" + p + "." + extension);
                    if (!f.exists()) {
                        return f;
                    } else {
                        p++;
                    }
                }
            }
        }
    }

}
