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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.storage.StorageUtils;
import java.io.IOException;
import java.io.InputStream;
import net.fichotheque.EditOrigin;
import net.mapeadores.util.exceptions.NestedIOException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.RelativePath;


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

    public final static String COMMANDNAME = "ResourceUpload";
    public final static String LOGO_COMMANDKEY = "_ CNF-06";
    public final static String ICON16_COMMANDKEY = "_ CNF-07";
    public final static String ICON32_COMMANDKEY = "_ CNF-08";
    public final static String FILE_PARAMNAME = "file";
    private RelativePath relativePath;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        FileValue fileValue = requestHandler.getRequestMap().getFileValue(FILE_PARAMNAME);
        if (fileValue == null) {
            throw BdfErrors.emptyMandatoryParameter(FILE_PARAMNAME);
        }
        boolean done = false;
        if (fileValue.length() > 0) {
            EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.ADMINISTRATION, COMMANDNAME);
            try (InputStream is = fileValue.getInputStream()) {
                StorageUtils.saveResource(bdfServer, relativePath, is, editOrigin);
            } catch (IOException ioe) {
                throw new NestedIOException(ioe);
            }
            done = true;
        }
        fileValue.free();
        if (done) {
            putResultObject(RELATIVEPATH_OBJ, relativePath);
            setDone("_ done.administration.resourceupload");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        relativePath = requestHandler.getMandatoryRelativePath();
    }

}
