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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.BdfServerEditor;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.externalsource.ExternalSourceType;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.ui.DataUi;
import fr.exemole.bdfserver.api.ui.UiComponents;
import fr.exemole.bdfserver.tools.externalsource.ExternalSourceUtils;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.ui.components.DataUiBuilder;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.tools.externalsource.ExternalSourceDefBuilder;
import net.fichotheque.tools.parsers.TypoParser;
import net.mapeadores.util.attr.AttributeParser;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.CleanedString;
import net.mapeadores.util.text.Label;
import net.mapeadores.util.text.LabelChange;
import net.mapeadores.util.text.LabelChangeBuilder;
import net.mapeadores.util.text.LabelUtils;
import net.mapeadores.util.text.TypoOptions;


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

    public final static String COMMANDNAME = "DataChangeCommand";
    public final static String COMMANDKEY = "_ CRP-34";
    public final static String NAME_PARAMNAME = "name";
    public final static String TITLE_PARAMPREFIX = "title/";
    public final static String PARAM_PARAMPREFIX = "param_";
    public final static String ATTRIBUTES_PARAMNAME = "attributes";
    private Corpus corpus;
    private UiComponents uiComponents;
    private DataUi dataUi;
    private LabelChange labelChange;
    private String attributes;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            done = updateDataUi(session.getBdfServerEditor(), dataUi);
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.datachange", dataUi.getDataName());
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        String name = getMandatory(NAME_PARAMNAME);
        uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        dataUi = (DataUi) uiComponents.getUiComponent(DataUi.toComponentName(name));
        if (dataUi == null) {
            throw BdfErrors.unknownParameterValue(NAME_PARAMNAME, name);
        }
        this.labelChange = requestHandler.getLabelChange(TITLE_PARAMPREFIX, false);
        this.attributes = getMandatory(ATTRIBUTES_PARAMNAME);
    }

    private boolean updateDataUi(BdfServerEditor bdfServerEditor, DataUi dataUi) throws ErrorMessageException {
        DataUiBuilder dataUiBuilder = DataUiBuilder.init(dataUi);
        LabelChangeBuilder labelChangeBuilder = dataUiBuilder.getLabelChangeBuilder();
        for (Label label : labelChange.getChangedLabels()) {
            Lang currentLang = label.getLang();
            TypoOptions typoOptions = TypoOptions.getTypoOptions(currentLang.toLocale());
            String labelString = label.getLabelString();
            String checkedLabelString = TypoParser.parseTypo(labelString, typoOptions);
            if (!checkedLabelString.equals(labelString)) {
                CleanedString cleanedString = CleanedString.newInstance(checkedLabelString);
                if (cleanedString == null) {
                    labelChangeBuilder.putRemovedLang(currentLang);
                    continue;
                } else {
                    label = LabelUtils.toLabel(currentLang, cleanedString);
                }
            }
            labelChangeBuilder.putLabel(label);
        }
        for (Lang lang : labelChange.getRemovedLangList()) {
            labelChangeBuilder.putRemovedLang(lang);
        }
        ExternalSourceType externalSourceType = ExternalSourceUtils.getMatchingExternalSourceType(dataUi.getExternalSourceDef());
        ExternalSourceDefBuilder externalSourceDefBuilder = dataUiBuilder.getExternalSourceDefBuilder();
        for (ExternalSourceType.Param param : externalSourceType.getParamList()) {
            String paramName = param.getName();
            String requestParamName = PARAM_PARAMPREFIX + paramName;
            if (requestHandler.hasParameter(requestParamName)) {
                externalSourceDefBuilder.addParam(paramName, requestHandler.getMandatoryParameter(requestParamName));
            } else {
                externalSourceDefBuilder.addParam(paramName, null);
            }
        }
        AttributeParser.parse(dataUiBuilder.getAttributeChangeBuilder(), attributes);
        bdfServerEditor.putComponentUi(uiComponents, dataUiBuilder.toDataUi());
        return true;
    }

}
