/* BdfServer_JsonProducers - 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.jsonproducers.exportation;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.instruction.BdfCommandResult;
import fr.exemole.bdfserver.api.instruction.BdfInstructionConstants;
import fr.exemole.bdfserver.api.instruction.OutputParameters;
import fr.exemole.bdfserver.api.interaction.domains.ExportationDomain;
import fr.exemole.bdfserver.tools.balayage.engine.BalayageLog;
import fr.exemole.bdfserver.tools.instruction.BdfCommandResultBuilder;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.instruction.OutputRequestHandler;
import fr.exemole.bdfserver.tools.instruction.ResultJsonProducer;
import java.text.ParseException;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import net.fichotheque.SubsetKey;
import net.fichotheque.exportation.balayage.BalayageContentDescription;
import net.fichotheque.exportation.balayage.BalayageDescription;
import net.fichotheque.exportation.table.TableExportContentDescription;
import net.fichotheque.exportation.table.TableExportDescription;
import net.fichotheque.exportation.transformation.TransformationKey;
import net.fichotheque.tools.exportation.scrutari.ScrutariExportUtils;
import net.mapeadores.util.json.JsonProducer;
import net.mapeadores.util.json.JsonProperty;
import net.mapeadores.util.json.JsonUtils;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.MessageLocalisation;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.LineLogs;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public final class ExportationJsonProducerFactory {

    private ExportationJsonProducerFactory() {
    }

    public static JsonProducer getJsonProducer(OutputParameters parameters) throws ErrorMessageException {
        OutputRequestHandler requestHandler = OutputRequestHandler.init(parameters);
        String json = parameters.getOutput();
        BdfCommandResult bdfCommandResult = parameters.getBdfCommandResult();
        BdfServer bdfServer = parameters.getBdfServer();
        if (bdfCommandResult == null) {
            switch (json) {
                case ExportationDomain.SCRUTARIEXPORT_JSON:
                    Map<SubsetKey, LineLogs> lineLogsMap = ScrutariExportUtils.checkFieldGeneration(requestHandler.getScrutariExportDef(), bdfServer.getTableExportContext());
                    if (!lineLogsMap.isEmpty()) {
                        bdfCommandResult = BdfCommandResultBuilder.init()
                                .putResultObject(BdfInstructionConstants.LINELOGSMAP_OBJ, lineLogsMap)
                                .toBdfCommandResult();
                    }
            }
        }
        ResultJsonProducer jsonProducer = new ResultJsonProducer(bdfCommandResult, parameters.getMessageLocalisation());
        JsonProperty jsonProperty = getJsonProperty(requestHandler, json, bdfCommandResult);
        if (jsonProperty == null) {
            return null;
        } else {
            jsonProducer.add(jsonProperty);
            return jsonProducer;
        }
    }

    private static JsonProperty getJsonProperty(OutputRequestHandler requestHandler, String name, BdfCommandResult bdfCommandResult) throws ErrorMessageException {
        BdfServer bdfServer = requestHandler.getBdfServer();
        Lang lang = requestHandler.getWorkingLang();
        MessageLocalisation messageLocalisation = requestHandler.getMessageLocalisation();
        switch (name) {
            case ExportationDomain.TABLEEXPORT_JSON: {
                return new TableExportJsonProperty(requestHandler.getTableExportDescription(), lang, messageLocalisation);
            }
            case ExportationDomain.TABLEEXPORT_ARRAY_JSON: {
                bdfServer.getTableExportManager().update();
                return new TableExportArrayJsonProperty(bdfServer, lang, messageLocalisation);
            }
            case ExportationDomain.TABLEEXPORT_CONTENT_JSON: {
                return new TableExportContentJsonProperty(bdfServer, getTableExportContentDescription(requestHandler), messageLocalisation);
            }
            case ExportationDomain.SCRUTARIEXPORT_JSON: {
                return new ScrutariExportJsonProperty(requestHandler.getScrutariExportDef(), lang);
            }
            case ExportationDomain.SCRUTARIEXPORT_ARRAY_JSON: {
                return new ScrutariExportArrayJsonProperty(bdfServer, lang);
            }
            case ExportationDomain.SCRUTARIEXPORT_PATHS_JSON: {
                return new ScrutariExportPathsJsonProperty(requestHandler.getScrutariExportDef(), requestHandler.getPathConfiguration());
            }
            case ExportationDomain.TRANSFORMATION_DESCRIPTION_JSON: {
                return new TransformationDescriptionJsonProperty(requestHandler.getTransformationDescription(), lang, messageLocalisation);
            }
            case ExportationDomain.TRANSFORMATION_DESCRIPTIONS_JSON: {
                bdfServer.getTransformationManager().update();
                return new TransformationDescriptionsJsonProperty(bdfServer.getTransformationManager(), getTransformationKeySet(requestHandler), lang, messageLocalisation);
            }
            case ExportationDomain.TRANSFORMATION_TEMPLATEDESCRIPTION_JSON: {
                return new TemplateDescriptionJsonProperty(requestHandler.getTemplateDescription(), lang, messageLocalisation);
            }
            case ExportationDomain.TRANSFORMATION_TEMPLATECONTENT_JSON: {
                return new TemplateContentJsonProperty(bdfServer, requestHandler.getTemplateContentDescription(), messageLocalisation);
            }
            case ExportationDomain.SQLEXPORT_JSON: {
                return new SqlExportJsonProperty(requestHandler.getSqlExportDef(), lang);
            }
            case ExportationDomain.SQLEXPORT_ARRAY_JSON: {
                return new SqlExportArrayJsonProperty(bdfServer, lang);
            }
            case ExportationDomain.SQLEXPORT_PATHS_JSON: {
                return new SqlExportPathsJsonProperty(requestHandler.getSqlExportDef(), requestHandler.getPathConfiguration());
            }
            case ExportationDomain.ACCESS_JSON: {
                return new AccessJsonProperty(requestHandler.getAccessDef(), lang);
            }
            case ExportationDomain.ACCESS_ARRAY_JSON: {
                return new AccessArrayJsonProperty(bdfServer, lang);
            }
            case ExportationDomain.BALAYAGE_JSON: {
                return new BalayageJsonProperty(requestHandler.getBalayageDescription(), lang, messageLocalisation);
            }
            case ExportationDomain.BALAYAGE_ARRAY_JSON: {
                bdfServer.getBalayageManager().update();
                return new BalayageArrayJsonProperty(bdfServer, lang, messageLocalisation);
            }
            case ExportationDomain.BALAYAGE_CONTENT_JSON: {
                return new BalayageContentJsonProperty(bdfServer, getBalayageContentDescription(requestHandler), messageLocalisation);
            }
            case ExportationDomain.BALAYAGE_LOG_JSON: {
                BalayageLog balayageLog = (BalayageLog) requestHandler.getResultObject(BdfInstructionConstants.BALAYAGELOG_OBJ);
                if (balayageLog != null) {
                    return balayageLog;
                } else {
                    return JsonUtils.EMPTY_JSONPROPERTY;
                }
            }
            default:
                return null;
        }
    }

    private static BalayageContentDescription getBalayageContentDescription(OutputRequestHandler requestHandler) throws ErrorMessageException {
        BalayageDescription balayageDescription = requestHandler.getMandatoryBalayageDescription();
        return requestHandler.getMandatoryBalayageContentDescription(balayageDescription);
    }

    private static TableExportContentDescription getTableExportContentDescription(OutputRequestHandler requestHandler) throws ErrorMessageException {
        TableExportDescription tableExportDescription = requestHandler.getMandatoryTableExportDescription();
        return requestHandler.getMandatoryTableExportContentDescription(tableExportDescription);
    }

    private static Set<TransformationKey> getTransformationKeySet(OutputRequestHandler requestHandler) throws ErrorMessageException {
        String[] keysArray = requestHandler.getTokens("keys");
        Set<TransformationKey> transformationKeySet = new LinkedHashSet<TransformationKey>();
        for (String keys : keysArray) {
            String[] tokens = StringUtils.getTechnicalTokens(keys, true);
            for (String token : tokens) {
                try {
                    transformationKeySet.add(TransformationKey.parse(token));
                } catch (ParseException pe) {
                    throw BdfErrors.unknownParameterValue("keys", token);
                }
            }
        }
        return transformationKeySet;
    }

}
