/* BdfServer_Commands - Copyright (c) 2026 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.edition;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.filesupload.FilesUploadEngine;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.io.IOException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "FilesUpload";
    public final static String FILES_PARAMNAME = "files";
    public final static String MODE_PARAMNAME = "mode";
    private String mode;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        FileValue[] files = requestHandler.getRequestMap().getFileValues(FILES_PARAMNAME);
        if ((files == null) || (files.length == 0)) {
            throw BdfErrors.emptyMandatoryParameter(FILES_PARAMNAME);
        }
        FilesUploadEngine engine = FilesUploadEngine.newInstance(bdfServer, mode);
        for (FileValue fileValue : files) {
            try {
                engine.addFileUpload(fileValue);
            } catch (IOException ioe) {
                throw BdfErrors.error("_ error.exception.io", ioe.getMessage());
            }
        }
        putResultObject(FILESUPLOADRESULT_OBJ, engine.getResult());
        setDone("_ done.edition.filesupload");
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        String mode = requestHandler.getMandatoryParameter(MODE_PARAMNAME);
        try {
            this.mode = FilesUploadEngine.checkMode(mode);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.wrongParameterValue(MODE_PARAMNAME, mode);
        }
    }

}
