/* BdfServer_Commands - Copyright (c) 2012-2024 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 java.text.ParseException;
import net.fichotheque.EditOrigin;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.io.ResourceUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.RelativePath;


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

    public final static String COMMANDNAME = "StreamTextChange";
    public final static String PATH_PARAMNAME = "path";
    public final static String CONTENT_PARAMNAME = "content";
    private RelativePath relativePath;
    private String text;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.ADMINISTRATION, COMMANDNAME);
        try (InputStream is = IOUtils.toInputStream(text, "UTF-8")) {
            StorageUtils.saveResource(bdfServer, relativePath, is, editOrigin);
        } catch (IOException ioe) {
            throw BdfErrors.error("_ error.exception.streamtext_io", ioe.getMessage());
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String path = getMandatory(PATH_PARAMNAME);
        try {
            relativePath = RelativePath.parse(path);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.resourcepath", path);
        }
        if (!ResourceUtils.isValidResourceRelativePath(relativePath)) {
            throw BdfErrors.error("_ error.wrong.resourcepath", path);
        }
        text = getMandatory(CONTENT_PARAMNAME);
    }

}
