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

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.FichothequeEditor;
import net.fichotheque.album.Illustration;
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 = "_ ALB-13";
    public final static String REMOVE_PARAMNAME = "remove";
    private Illustration illustration;
    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.ALBUM, COMMANDNAME)) {
            FichothequeEditor fichothequeEditor = session.getFichothequeEditor();
            fichothequeEditor.getJunctionEditor().updateJunctions(illustration, junctionChanges);
        }
        putResultObject(ALBUM_OBJ, illustration.getAlbum());
        putResultObject(ILLUSTRATION_OBJ, illustration);
        setDone("_ done.album.junctionremove");
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        illustration = requestHandler.getMandatoryIllustration();
        getPermissionChecker()
                .checkWrite(illustration);
        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(requestHandler.getPermissionSummary()));
    }

}
