/* BdfServer_Commands - Copyright (c) 2022-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 static fr.exemole.bdfserver.api.instruction.BdfInstructionConstants.TEMPLATEDESCRIPTION_OBJ;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.managers.TransformationManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.storage.TemplateStorageUnitBuilder;
import java.io.IOException;
import java.text.ParseException;
import net.fichotheque.EditOrigin;
import net.fichotheque.SubsetKey;
import net.fichotheque.exportation.transformation.TemplateContentDescription;
import net.fichotheque.exportation.transformation.TemplateDef;
import net.fichotheque.exportation.transformation.TemplateDescription;
import net.fichotheque.exportation.transformation.TemplateKey;
import net.fichotheque.exportation.transformation.TransformationKey;
import net.fichotheque.utils.TransformationUtils;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "TemplateDuplicate";
    public final static String COMMANDKEY = "_ EXP-37";
    public final static String NEW_TEMPLATE_PARAMNAME = "newtemplate";
    public final static String DESTINATION_CORPUS_PARAMNAME = "destinationcorpus";
    private TemplateDescription originTemplateDescription;
    private TemplateKey destinationTemplateKey;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.EXPORTATION, COMMANDNAME);
        TemplateDef destinationTemplateDef = TransformationUtils.deriveTemplateDef(originTemplateDescription.getTemplateDef(), destinationTemplateKey);
        TemplateStorageUnitBuilder builder = TemplateStorageUnitBuilder.init(originTemplateDescription.getType(), destinationTemplateDef);
        TemplateKey originTemplateKey = originTemplateDescription.getTemplateKey();
        TransformationManager transformationManager = bdfServer.getTransformationManager();
        for (TemplateContentDescription templateContentDescription : originTemplateDescription.getTemplateContentDescriptionList()) {
            String path = templateContentDescription.getPath();
            builder.addStorageContent(transformationManager.getTemplateStorageContent(originTemplateKey, path));
        }
        try {
            TemplateDescription templateDescription = transformationManager.createTemplate(builder.toTemplateStorageUnit(), editOrigin);
            putResultObject(TEMPLATEDESCRIPTION_OBJ, templateDescription);
            setDone("_ done.exportation.templateduplicate", templateDescription.getTemplateKey().getKeyString());
        } catch (IOException ioe) {
            throw BdfErrors.error("_ error.exception.templatecontent_io", ioe.getMessage());
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        this.originTemplateDescription = requestHandler.getMandatoryTemplateDescription();
        String templateName = getMandatory(NEW_TEMPLATE_PARAMNAME);
        templateName = templateName.trim();
        if (templateName.length() == 0) {
            throw BdfErrors.error("_ error.empty.templatename", templateName);
        }
        if (!StringUtils.isTechnicalName(templateName, true)) {
            throw BdfErrors.error("_ error.wrong.templatename", templateName);
        }
        TemplateKey originTemplateKey = originTemplateDescription.getTemplateKey();
        TransformationKey destinationTransformationKey = originTemplateKey.getTransformationKey();
        if (destinationTransformationKey.isCorpusTransformationKey()) {
            String destinationCorpusName = requestHandler.getTrimedParameter(DESTINATION_CORPUS_PARAMNAME);
            if (!destinationCorpusName.isEmpty()) {
                try {
                    SubsetKey corpusKey = SubsetKey.parse(SubsetKey.CATEGORY_CORPUS, destinationCorpusName);
                    if (!fichotheque.containsSubset(corpusKey)) {
                        throw BdfErrors.unknownParameterValue(DESTINATION_CORPUS_PARAMNAME, destinationCorpusName);
                    }
                    destinationTransformationKey = new TransformationKey(corpusKey);
                } catch (ParseException pe) {
                    throw BdfErrors.wrongParameterValue(DESTINATION_CORPUS_PARAMNAME, destinationCorpusName);
                }
            }
        }
        try {
            this.destinationTemplateKey = TemplateKey.parse(destinationTransformationKey, originTemplateKey.getValidExtension(), templateName);
        } catch (ParseException pe) {
            throw new ShouldNotOccurException("Test done before");
        }
        if (bdfServer.getTransformationManager().containsTemplate(destinationTemplateKey)) {
            throw BdfErrors.error("_ error.existing.template", templateName);
        }
    }

}
