/* BdfServer_Commands - Copyright (c) 2011-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.interaction.Domains;
import fr.exemole.bdfserver.api.ui.IncludeUi;
import fr.exemole.bdfserver.api.ui.SpecialIncludeUi;
import fr.exemole.bdfserver.api.ui.UiComponents;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.ui.components.IncludeUiBuilder;
import java.text.ParseException;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.include.ExtendedIncludeKey;
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 IncludeChangeCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "IncludeChange";
    public final static String COMMANDKEY = "_ CRP-13";
    public final static String CUSTOM_PARAMNAME = "custom";
    public final static String KEY_PARAMNAME = "key";
    public final static String TITLE_PARAMPREFIX = "title/";
    public final static String ATTRIBUTES_PARAMNAME = "attributes";
    private UiComponents uiComponents;
    private IncludeUi includeUi;
    private Corpus corpus;
    private boolean custom = false;
    private LabelChange labelChange;
    private String attributes;

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

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

    @Override
    protected void doCommand() {
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            done = updateIncludeUi(session.getBdfServerEditor(), includeUi);
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.includechange", includeUi.getName());
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        String key = getMandatory(KEY_PARAMNAME);
        uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        includeUi = getIncludeUi(key);
        if (includeUi == null) {
            throw BdfErrors.unknownParameterValue(KEY_PARAMNAME, key);
        }
        custom = requestHandler.isTrue(CUSTOM_PARAMNAME);
        if (custom) {
            labelChange = requestHandler.getLabelChange(TITLE_PARAMPREFIX, false);
        }
        this.attributes = getMandatory(ATTRIBUTES_PARAMNAME);
    }

    private IncludeUi getIncludeUi(String key) throws ErrorMessageException {
        try {
            key = SpecialIncludeUi.checkSpecialIncludeName(key);
            return (IncludeUi) uiComponents.getUiComponent(key);
        } catch (IllegalArgumentException iae) {
            try {
                ExtendedIncludeKey includeKey = ExtendedIncludeKey.parse(key);
                return (IncludeUi) uiComponents.getUiComponent(includeKey);
            } catch (ParseException pe) {
                throw BdfErrors.wrongParameterValue(KEY_PARAMNAME, key);
            }
        }
    }

    private boolean updateIncludeUi(BdfServerEditor bdfServerEditor, IncludeUi includeUi) {
        IncludeUiBuilder includeUiBuilder = IncludeUiBuilder.init(includeUi);
        LabelChangeBuilder labelChangerBuilder = includeUiBuilder.getLabelChangeBuilder();
        if (!custom) {
            includeUiBuilder.getLabelChangeBuilder().clear();
        } else {
            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) {
                        labelChangerBuilder.putRemovedLang(currentLang);
                        continue;
                    } else {
                        label = LabelUtils.toLabel(currentLang, cleanedString);
                    }
                }
                labelChangerBuilder.putLabel(label);
            }
            for (Lang lang : labelChange.getRemovedLangList()) {
                labelChangerBuilder.putRemovedLang(lang);
            }
        }
        AttributeParser.parse(includeUiBuilder.getAttributeChangeBuilder(), attributes);
        bdfServerEditor.putComponentUi(uiComponents, includeUiBuilder.toIncludeUi());
        return true;
    }

}
