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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.EditOrigin;
import net.fichotheque.exportation.balayage.BalayageDef;
import net.fichotheque.exportation.balayage.BalayageDescription;
import net.fichotheque.tools.exportation.balayage.BalayageDefBuilder;
import net.fichotheque.tools.exportation.balayage.BalayagePostscriptumBuilder;
import net.fichotheque.tools.exportation.balayage.dom.BalayageUnitsDOMReader;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.LangsUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.LogUtils;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.xml.DOMUtils;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


/**
 *
 * @author Vincent Calame
 */
public class BalayageDefChangeCommand extends AbstractDefChangeCommand {

    public final static String COMMANDNAME = "BalayageDefChange";
    public final static String COMMANDKEY = "_ EXP-53";
    public final static String LANGS_PARAMNAME = "langs";
    public final static String DEFAULTLANGOPTION_PARAMNAME = "defaultlangoption";
    public final static String IGNORETRANSFORMATION = "ignoretransformation";
    public final static String UNITSXML = "unitsxml";
    public final static String SCRIPT = "script";
    public final static String SCRUTARI = "scrutari";
    public final static String SQL = "sql";
    private BalayageDef balayageDef;

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

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

    @Override
    protected void doCommand() {
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.EXPORTATION, COMMANDNAME);
        BalayageDescription balayageDescription = bdfServer.getBalayageManager().putBalayageDef(balayageDef, editOrigin);
        putResultObject(BALAYAGEDESCRIPTION_OBJ, balayageDescription);
        setDone("_ done.exportation.balayagedefchange", balayageDef.getName());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        BalayageDescription balayageDescription = requestHandler.getMandatoryBalayageDescription();
        String defaultLangOption = getMandatory(DEFAULTLANGOPTION_PARAMNAME);
        String langs = getMandatory(LANGS_PARAMNAME);
        boolean ignoreTransformation = requestHandler.isTrue(IGNORETRANSFORMATION);
        BalayageDefBuilder balayageDefBuilder = BalayageDefBuilder.init(balayageDescription.getName(), balayageDescription.getBalayageDef().getAttributes())
                .setTargetName(getTargetName())
                .setTargetPath(getTargetPath())
                .setIgnoreTransformation(ignoreTransformation);
        try {
            balayageDefBuilder.setDefaultLangOption(defaultLangOption);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.wrongParameterValue(DEFAULTLANGOPTION_PARAMNAME, defaultLangOption);
        }
        for (Lang lang : LangsUtils.toCleanLangArray(langs)) {
            balayageDefBuilder.addLang(lang);
        }
        BalayagePostscriptumBuilder balayagePostscriptumBuilder = balayageDefBuilder.getBalayagePostscriptumBuilder();
        checkScript(balayagePostscriptumBuilder);
        checkScrutari(balayagePostscriptumBuilder);
        checkSql(balayagePostscriptumBuilder);
        checkUnitsXml(balayageDefBuilder);
        checkSelectionOptions(balayageDefBuilder.getSelectionOptionsBuilder());
        checkDefBuilder(balayageDefBuilder);
        this.balayageDef = balayageDefBuilder.toBalayageDef();
    }

    private void checkScript(BalayagePostscriptumBuilder balayagePostscriptumBuilder) throws ErrorMessageException {
        String[] values = requestHandler.getTokens(SCRIPT);
        for (String value : values) {
            balayagePostscriptumBuilder.addExternalScript(value);
        }
    }

    private void checkScrutari(BalayagePostscriptumBuilder balayagePostscriptumBuilder) throws ErrorMessageException {
        String[] values = requestHandler.getTokens(SCRUTARI);
        for (String value : values) {
            balayagePostscriptumBuilder.addScrutariExport(value);
        }
    }

    private void checkSql(BalayagePostscriptumBuilder balayagePostscriptumBuilder) throws ErrorMessageException {
        String[] values = requestHandler.getTokens(SQL);
        for (String value : values) {
            balayagePostscriptumBuilder.addSqlExport(value);
        }
    }

    private void checkUnitsXml(BalayageDefBuilder balayageDefBuilder) throws ErrorMessageException {
        String unitsXml = requestHandler.getTrimedParameter(UNITSXML);
        if (unitsXml.isEmpty()) {
            return;
        }
        unitsXml = "<units>" + unitsXml + "</units>";
        try {
            Document document = DOMUtils.parseDocument(unitsXml);
            BalayageUnitsDOMReader.init(fichotheque, balayageDefBuilder, LogUtils.NULL_MESSAGEHANDLER)
                    .read(document.getDocumentElement());
        } catch (SAXException saxException) {
            throw BdfErrors.error("_ error.wrong.unitsxml", saxException.getMessage());
        }
    }


}
