/* BdfServer_Commands - Copyright (c) 2014-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.BdfErrors;
import java.text.ParseException;
import net.fichotheque.FichothequeEditor;
import net.fichotheque.album.Album;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.corpus.metadata.CorpusField;
import net.fichotheque.corpus.metadata.FieldKey;
import net.fichotheque.corpus.metadata.FieldOptionConstants;
import net.fichotheque.include.IncludeKey;
import net.fichotheque.tools.conversion.imagetoillustration.ImageToIllustrationConverter;
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 ImageToIllustrationCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "ImageToIllustration";
    public final static String COMMANDKEY = "_ CRP-26";
    public final static String FIELD_PARAMNAME = "field";
    public final static String ALBUMINCLUDE_PARAMNAME = "albuminclude";
    public final static String BASEURL_PARAMNAME = "baseurl";
    public final static String MODE_PARAMNAME = "mode";
    public final static String RUN_MODE_PARAMVALUE = "run";
    public final static String TEST_MODE_PARAMVALUE = "test";
    private Corpus corpus;
    private Album album;
    private CorpusField sourceField;
    private IncludeKey albumIncludeKey;
    private String baseUrl;
    private boolean testOnly;

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

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

    @Override
    protected void doCommand() {
        SourceLogsBuilder logsBuilder = new SourceLogsBuilder();
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            FichothequeEditor fichothequeEditor = session.getFichothequeEditor();
            ImageToIllustrationConverter imageToIllustrationConverter = new ImageToIllustrationConverter(fichothequeEditor.getAlbumEditor(album), fichothequeEditor.getCroisementEditor(), logsBuilder, testOnly);
            for (FicheMeta ficheMeta : corpus.getFicheMetaList()) {
                imageToIllustrationConverter.convert(ficheMeta, sourceField.getFieldKey(), baseUrl, albumIncludeKey.getMode(), albumIncludeKey.getWeightFilter());
            }
        }
        String messageKey;
        if (testOnly) {
            messageKey = "_ done.corpus.imagetoillustration_test";
        } else {
            messageKey = "_ done.corpus.imagetoillustration_run";
        }
        setCommandMessage(CommandMessageBuilder.init()
                .setCommandLogs(logsBuilder.toSourceLogs())
                .setDone(messageKey)
                .toCommandMessage());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        corpus = requestHandler.getMandatoryCorpus();
        baseUrl = getMandatory(BASEURL_PARAMNAME).trim();
        String fieldParamName = getMandatory(FIELD_PARAMNAME);
        try {
            FieldKey fieldKey = FieldKey.parse(fieldParamName);
            sourceField = corpus.getCorpusMetadata().getCorpusField(fieldKey);
            if (sourceField == null) {
                throw BdfErrors.unknownParameterValue(FIELD_PARAMNAME, fieldParamName);
            }
        } catch (ParseException pe) {
            throw BdfErrors.wrongParameterValue(FIELD_PARAMNAME, fieldParamName);
        }
        switch (sourceField.getFicheItemType()) {
            case CorpusField.ITEM_FIELD:
            case CorpusField.IMAGE_FIELD:
                break;
            default:
                throw BdfErrors.error("_ error.unsupported.ficheitemtype", fieldParamName);
        }
        if ((baseUrl.isEmpty()) && (sourceField.isType(CorpusField.IMAGE_FIELD))) {
            String value = sourceField.getStringOption(FieldOptionConstants.BASEURL_OPTION);
            if (value != null) {
                baseUrl = value;
            }
        }
        String modeString = getMandatory(MODE_PARAMNAME);
        if (modeString.equals(RUN_MODE_PARAMVALUE)) {
            testOnly = false;
        } else {
            testOnly = true;
        }
        String albumIncludeKeyString = getMandatory(ALBUMINCLUDE_PARAMNAME);
        try {
            albumIncludeKey = IncludeKey.parse(albumIncludeKeyString);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.includekey", albumIncludeKeyString);
        }
        if (!albumIncludeKey.getSubsetKey().isAlbumSubset()) {
            throw BdfErrors.error("_ error.unsupported.subsetcategory", albumIncludeKeyString);
        }
        album = (Album) fichotheque.getSubset(albumIncludeKey.getSubsetKey());
        if (album == null) {
            throw BdfErrors.error("_ error.unknown.album", albumIncludeKeyString);
        }
    }

}
