/* BdfServer_Commands - Copyright (c) 2015-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.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.text.tableparser.TableParser;


/**
 *
 * @author Vincent Calame
 */
public abstract class AbstractImportParseCommand extends AbstractBdfCommand {

    public final static String FIELDSORIGIN_PARAMNAME = "fieldsorigin";
    public final static String INPUT_FIELDSORIGIN_PARAMVALUE = "input";
    public final static String FIRSTLINE_FIELDSORIGIN_PARAMVALUE = "firstline";
    public final static String FIELDS_PARAMNAME = "fields";
    public final static String CONTENT_PARAMNAME = "content";
    public final static String FILE_PARAMNAME = "file";
    public final static String CHARSET_PARAMNAME = "charset";
    protected String[] fieldsArray;
    protected String[][] lines;

    public AbstractImportParseCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);

    }

    protected void checkLines() throws ErrorMessageException {
        String fieldsOrigin = getMandatory(FIELDSORIGIN_PARAMNAME);
        boolean inputFieldsOrigin = fieldsOrigin.equals(INPUT_FIELDSORIGIN_PARAMVALUE);
        TableParser.Parameters tableParserParameters = requestHandler.getTableParserParameters();
        String fieldsValue = requestHandler.getParameter(FIELDS_PARAMNAME, inputFieldsOrigin);
        String charset = requestHandler.getTrimedParameter(CHARSET_PARAMNAME);
        requestHandler.disableStore();
        String contentString = getContent(charset);

        this.lines = TableParser.parse(contentString, tableParserParameters);
        if (inputFieldsOrigin) {
            this.fieldsArray = StringUtils.getTechnicalTokens(fieldsValue, true);
        } else {
            int length = lines.length;
            if (length == 0) {
                this.fieldsArray = new String[0];
            } else {
                this.fieldsArray = lines[0];
                String[][] tempo = new String[length - 1][];
                System.arraycopy(lines, 1, tempo, 0, length - 1);
                this.lines = tempo;
            }
        }
    }

    private String getContent(String charset) throws ErrorMessageException {
        FileValue fileValue = requestHandler.getRequestMap().getFileValue(FILE_PARAMNAME);
        if (fileValue == null) {
            return getMandatory(CONTENT_PARAMNAME);
        }
        try {
            String content = getContent(fileValue, charset);
            fileValue.free();
            return content;
        } catch (ErrorMessageException eme) {
            fileValue.free();
            throw eme;
        }
    }

    private String getContent(FileValue fileValue, String charset) throws ErrorMessageException {
        if (!charset.isEmpty()) {
            boolean supported;
            try {
                supported = Charset.isSupported(charset);
            } catch (IllegalCharsetNameException icne) {
                supported = false;
            }
            if (!supported) {
                throw BdfErrors.wrongParameterValue(CHARSET_PARAMNAME, charset);
            }
        } else {
            charset = "UTF-8";
        }
        try (InputStream is = fileValue.getInputStream()) {
            return IOUtils.toString(is, charset);
        } catch (IOException ioe) {
            throw BdfErrors.ioException(ioe);
        }
    }

}
