/* BdfServer_Commands - Copyright (c) 2015-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.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.addenda.Document;
import net.fichotheque.junction.JunctionChanges;
import net.fichotheque.tools.junction.JunctionRemoveParser;
import net.fichotheque.tools.permission.PermissionPredicate;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "JunctionRemove";
    public final static String COMMANDKEY = "_ ADD-08";
    public final static String REMOVE_PARAMNAME = "remove";
    private Document document;
    private JunctionChanges junctionChanges;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        try (EditSession session = startEditSession(Domains.ADDENDA, COMMANDNAME)) {
            session.getFichothequeEditor().getJunctionEditor().updateJunctions(document, junctionChanges);
        }
        putResultObject(ADDENDA_OBJ, document.getAddenda());
        putResultObject(DOCUMENT_OBJ, document);
        setDone("_ done.addenda.junctionremove");
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        document = requestHandler.getMandatoryDocument();
        getPermissionChecker()
                .checkWrite(document);
        if (!checkConfirmation()) {
            throw BdfErrors.error("_ error.empty.confirmationcheck_remove");
        }
        String[] values = requestHandler.getTokens(REMOVE_PARAMNAME);
        if (values.length == 0) {
            throw BdfErrors.error("_ error.empty.ficheselection");
        }
        junctionChanges = JunctionRemoveParser.parseRemove(values, fichotheque, PermissionPredicate.read(getPermissionSummary()));
    }

}
