/* BdfServer_Commands - Copyright (c) 2012-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 fr.exemole.bdfserver.api.exportation.table.FicheTableParameters;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.managers.TableExportManager;
import fr.exemole.bdfserver.tools.exportation.table.DefaultTableDefFactory;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import java.util.LinkedHashSet;
import java.util.Set;
import net.fichotheque.EditOrigin;
import net.fichotheque.SubsetKey;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.exportation.table.TableDef;
import net.fichotheque.exportation.table.TableExportDescription;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.utils.EligibilityUtils;
import net.fichotheque.utils.FichothequeUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "TableExportCreation";
    public final static String COMMANDKEY = "_ EXP-11";
    public final static String NEWTABLEEXPORT_PARAMNAME = "newtableexport";
    public final static String CORPUSLIST_PARAMNAME = "corpuslist";
    public final static String THESAURUSLIST_PARAMNAME = "thesauruslist";
    private FicheTableParameters ficheTableParameters;
    private String newTableExportName;
    private Corpus[] corpusArray;
    private Thesaurus[] thesaurusArray;

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

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

    @Override
    protected void doCommand() {
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.EXPORTATION, COMMANDNAME);
        TableExportManager manager = bdfServer.getTableExportManager();
        TableExportDescription tableExportDescription = null;
        if (corpusArray != null) {
            for (Corpus corpus : corpusArray) {
                TableDef tableDef = DefaultTableDefFactory.fromUi(bdfServer, corpus, ficheTableParameters, getPermissionSummary());
                tableExportDescription = manager.putTableDef(newTableExportName, corpus.getSubsetKey(), tableDef, editOrigin);
            }
        }
        if (thesaurusArray != null) {
            for (Thesaurus thesaurus : thesaurusArray) {
                TableDef tableDef = DefaultTableDefFactory.fromThesaurusMetadata(thesaurus, bdfServer.getThesaurusLangChecker());
                tableExportDescription = manager.putTableDef(newTableExportName, thesaurus.getSubsetKey(), tableDef, editOrigin);
            }
        }
        if (tableExportDescription != null) {
            putResultObject(TABLEEXPORTDESCRIPTION_OBJ, tableExportDescription);
            setDone("_ done.exportation.tableexportcreation", newTableExportName);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        newTableExportName = getMandatory(NEWTABLEEXPORT_PARAMNAME).trim();
        if (newTableExportName.length() == 0) {
            throw BdfErrors.error("_ error.empty.exportname");
        }
        if (!StringUtils.isTechnicalName(newTableExportName, true)) {
            throw BdfErrors.error("_ error.wrong.exportname", newTableExportName);
        }
        if (bdfServer.getTableExportManager().containsTableExport(newTableExportName)) {
            throw BdfErrors.error("_ error.existing.tableexport", newTableExportName);
        }
        ficheTableParameters = requestHandler.getFicheTableParameters();
        String[] corpusNames = requestHandler.getTokens(CORPUSLIST_PARAMNAME);
        if (corpusNames.length > 0) {
            Set<Corpus> set = new LinkedHashSet<Corpus>();
            for (String corpusName : corpusNames) {
                SubsetKey corpusKey;
                try {
                    corpusKey = SubsetKey.parse(SubsetKey.CATEGORY_CORPUS, corpusName);
                    Corpus corpus = (Corpus) fichotheque.getSubset(corpusKey);
                    if (corpus != null) {
                        set.add(corpus);
                    }
                } catch (ParseException pe) {
                }
            }
            this.corpusArray = set.toArray(new Corpus[set.size()]);
        }
        String[] thesaurusNames = requestHandler.getTokens(THESAURUSLIST_PARAMNAME);
        if (thesaurusNames.length > 0) {
            Set<Thesaurus> set = new LinkedHashSet<Thesaurus>();
            for (String thesaurusName : thesaurusNames) {
                SubsetKey thesaurusKey;
                try {
                    thesaurusKey = SubsetKey.parse(SubsetKey.CATEGORY_THESAURUS, thesaurusName);
                    Thesaurus thesaurus = (Thesaurus) fichotheque.getSubset(thesaurusKey);
                    if (thesaurus != null) {
                        set.add(thesaurus);
                    }
                } catch (ParseException pe) {
                }
            }
            this.thesaurusArray = set.toArray(new Thesaurus[set.size()]);
        }
        if ((thesaurusNames.length == 0) && ((corpusNames.length == 0))) {
            this.corpusArray = FichothequeUtils.toCorpusArray(fichotheque, EligibilityUtils.ALL_SUBSET_PREDICATE);
        }
    }

}
