/* BdfServer_Commands - Copyright (c) 2013-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.importation;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.BdfServerUtils;
import fr.exemole.bdfserver.tools.importation.ImportationEngine;
import fr.exemole.bdfserver.tools.importation.ImportationFileUtils;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.users.BdfUserUtils;
import java.io.File;
import java.io.IOException;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.fiche.FicheItems;
import net.fichotheque.importation.CorpusImport;
import net.fichotheque.tools.importation.ParseResultBuilder;
import net.fichotheque.tools.importation.directory.CorpusImportSave;
import net.fichotheque.tools.importation.parsers.corpus.CorpusRowParser;
import net.fichotheque.tools.importation.parsers.ImportationParseContext;
import net.fichotheque.tools.importation.parsers.Row;
import net.fichotheque.tools.parsers.FicheItemParser;
import net.fichotheque.tools.parsers.FicheParser;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.text.TypoOptions;


/**
 *
 * @author Vincent Calame
 */
public class CorpusImportParseCommand extends AbstractImportParseCommand {

    public final static String COMMANDNAME = "CorpusImportParse";
    public final static String COMMANDKEY = "_ IMP-01";
    public final static String TYPE_PARAMNAME = "type";
    public final static String DEFAULTOWNERS_PARAMNAME = "defaultowners";
    private String parseType;
    private Corpus corpus;
    private FicheItems defaultOwners;


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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        FicheParser ficheParser = new FicheParser(BdfServerUtils.getFicheParserParameters(bdfServer, bdfUser));
        ParseResultBuilder parseResultBuilder = new ParseResultBuilder(ImportationEngine.CORPUS_IMPORT);
        ImportationParseContext parseContext = ImportationParseContext.init(bdfServer.getFichothequeQuestioner(), bdfServer.getThesaurusLangChecker(), bdfUser.getWorkingLang())
                .setPolicyProvider(bdfServer.getPolicyManager().getPolicyProvider())
                .setDefaultOwners(defaultOwners);
        CorpusRowParser rowParser = CorpusRowParser.newInstance(fieldsArray, parseType, corpus, parseResultBuilder, ficheParser, parseContext);
        if (rowParser != null) {
            for (int i = 0; i < lines.length; i++) {
                String[] line = lines[i];
                if (line.length != 0) {
                    rowParser.parseRow(i + 1, new Row(line));
                }
            }
            CorpusImport corpusImport = rowParser.getCorpusImportBuilder().toCorpusImport();
            try {
                switch (corpusImport.getType()) {
                    case CorpusImport.EDIT_TYPE:
                        File tmpDir = ImportationFileUtils.createTmpDir(bdfServer, "corpusimport");
                        CorpusImportSave.save(corpusImport, tmpDir);
                        parseResultBuilder.setPath(tmpDir.getName());
                        break;
                    default:
                        File tmpFile = ImportationFileUtils.saveTmpXml(bdfServer, corpusImport);
                        parseResultBuilder.setPath(tmpFile.getName());
                }
            } catch (IOException ioe) {
                throw BdfErrors.ioException(ioe);
            }
        }
        putResultObject(PARSERESULT_OBJ, parseResultBuilder.toParseResult());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        requestHandler.enableStore();
        String typeParam = getMandatory(TYPE_PARAMNAME);
        try {
            typeParam = CorpusRowParser.checkType(typeParam);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.wrongParameterValue(TYPE_PARAMNAME, typeParam);
        }
        this.parseType = typeParam;
        this.corpus = requestHandler.getMandatoryCorpus();
        if (parseType.equals(CorpusRowParser.CREATION_TYPE)) {
            this.defaultOwners = getDefaultOwners();
        }
        checkLines();
        requestHandler.store("form_import_corpus");
    }

    private FicheItems getDefaultOwners() {
        TypoOptions typoOptions = BdfUserUtils.getTypoOptions(bdfUser);
        String[] ownerTokens = StringUtils.getTechnicalTokens(requestHandler.getTrimedParameter(DEFAULTOWNERS_PARAMNAME), ';', false);
        FicheItems items = FicheItemParser.parsePersonList(ownerTokens, bdfServer.getFichothequeQuestioner(), bdfUser.getRedacteur().getSubsetKey(), typoOptions);
        if (items.isEmpty()) {
            return null;
        } else {
            return items;
        }
    }


}
