/* 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.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfCommandUtils;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.CorpusEditor;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.corpus.fiche.Fiche;
import net.fichotheque.corpus.metadata.CorpusField;
import net.fichotheque.corpus.metadata.CorpusMetadata;
import net.fichotheque.corpus.metadata.CorpusMetadataEditor;
import net.fichotheque.corpus.metadata.ExistingFieldKeyException;
import net.fichotheque.corpus.metadata.FieldKey;
import net.fichotheque.corpus.metadata.FieldOptionConstants;
import net.fichotheque.corpus.metadata.FieldOptionException;
import net.fichotheque.tools.conversion.fieldtofield.FieldToFieldConverter;
import net.fichotheque.tools.corpus.CorpusTools;
import net.fichotheque.tools.corpus.FieldGenerationEngine;
import net.mapeadores.util.exceptions.ImplementationException;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.CommandMessageBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.SourceLogsBuilder;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "Conversion";
    public final static String COMMANDKEY = "_ CRP-22";
    public final static String FIELD_PARAMNAME = "field";
    public final static String NEWCATEGORY_PARAMNAME = "newcategory";
    public final static String NEWNAME_PARAMNAME = "newname";
    private Corpus corpus;
    private CorpusField sourceField;
    private FieldKey newFieldKey;

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

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

    @Override
    protected void doCommand() {
        SourceLogsBuilder logsBuilder = new SourceLogsBuilder();
        int ficheCount = 0;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            CorpusField newCorpusField = null;
            CorpusEditor corpusEditor = session.getFichothequeEditor().getCorpusEditor(corpus);
            CorpusMetadataEditor corpusMetadataEditor = corpusEditor.getCorpusMetadataEditor();
            try {
                String ficheItemType = getFicheItemType();
                newCorpusField = corpusMetadataEditor.createCorpusField(newFieldKey, ficheItemType);
                if ((newCorpusField.isInfo()) && (sourceField.isSection())) {
                    corpusMetadataEditor.setFieldOption(newCorpusField, FieldOptionConstants.INFODISPLAY_OPTION, FieldOptionConstants.BLOCK_DISPLAY);
                }
            } catch (ExistingFieldKeyException efke) {
                throw new ShouldNotOccurException("test before ExistingSubsetException");
            } catch (FieldOptionException foe) {
                throw new ImplementationException(foe);
            }
            FieldToFieldConverter fieldToFieldConverter = FieldToFieldConverter.getInstance(sourceField, newCorpusField, logsBuilder);
            FieldGenerationEngine engine = BdfCommandUtils.buildEngine(this, corpus);
            for (FicheMeta ficheMeta : corpus.getFicheMetaList()) {
                Fiche fiche = corpus.getFiche(ficheMeta);
                fieldToFieldConverter.convert(ficheMeta, fiche);
                CorpusTools.saveFiche(corpusEditor, ficheMeta, fiche, engine, false);
                ficheCount++;
            }
        }
        putResultObject(CORPUS_OBJ, corpus);
        setCommandMessage(CommandMessageBuilder.init()
                .setCommandLogs(logsBuilder.toSourceLogs())
                .setDone("_ done.corpus.conversion", sourceField.getFieldString(), newFieldKey.getKeyString(), ficheCount)
                .toCommandMessage());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        CorpusMetadata corpusMetadata = corpus.getCorpusMetadata();
        String fieldParamName = getMandatory(FIELD_PARAMNAME);
        try {
            FieldKey fieldKey = FieldKey.parse(fieldParamName);
            sourceField = corpusMetadata.getCorpusField(fieldKey);
            if (sourceField == null) {
                throw BdfErrors.unknownParameterValue(FIELD_PARAMNAME, fieldParamName);
            }
        } catch (ParseException pe) {
            throw BdfErrors.wrongParameterValue(FIELD_PARAMNAME, fieldParamName);
        }
        short fieldCategory = getFieldCategory();
        String newName = getMandatory(NEWNAME_PARAMNAME);
        try {
            newFieldKey = FieldKey.parse(fieldCategory, newName);
            if (corpusMetadata.getCorpusField(newFieldKey) != null) {
                throw BdfErrors.error("_ error.existing.fieldkey", newFieldKey.getKeyString());
            }
            if (newFieldKey.isSpecial()) {
                throw BdfErrors.wrongParameterValue(NEWNAME_PARAMNAME, newName);
            }
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.fieldkey", newName);
        }
    }

    private short getFieldCategory() throws ErrorMessageException {
        String categoryString = getMandatory(NEWCATEGORY_PARAMNAME);
        try {
            short category = FieldKey.categoryToShort(categoryString);
            switch (category) {
                case FieldKey.PROP_CATEGORY:
                case FieldKey.INFO_CATEGORY:
                case FieldKey.SECTION_CATEGORY:
                    return category;
                default:
                    throw BdfErrors.wrongParameterValue(NEWCATEGORY_PARAMNAME, categoryString);
            }
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.wrongParameterValue(NEWCATEGORY_PARAMNAME, categoryString);
        }
    }

    private String getFicheItemType() {
        if (newFieldKey.isSection()) {
            return "";
        }
        FieldKey sourceFieldKey = sourceField.getFieldKey();
        if (sourceFieldKey.isSection()) {
            return CorpusField.PARA_FIELD;
        }
        String current = sourceField.getFicheItemType();
        if (current.isEmpty()) {
            return CorpusField.ITEM_FIELD;
        }
        return current;
    }

}
