/* BdfServer_HtmlProducers - 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.htmlproducers.importation;

import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.commands.importation.AbstractImportParseCommand;
import fr.exemole.bdfserver.html.consumers.Grid;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import net.fichotheque.importation.ParseResult;
import net.mapeadores.util.html.HtmlPrinter;
import net.mapeadores.util.logging.LineLog;
import net.mapeadores.util.logging.LineLogs;
import net.mapeadores.util.logging.LineMessage;
import net.mapeadores.util.logging.LogUtils;
import net.mapeadores.util.logging.SourceLog;
import net.mapeadores.util.logging.SourceMessage;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.text.tableparser.CsvParameters;
import net.mapeadores.util.text.tableparser.TableParser;


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

    private ImportationHtmlUtils() {
    }

    public static boolean printParseResult(HtmlPrinter hp, ParseResult parseResult) {
        SourceLog columnLog = parseResult.getColumnLog();
        if (!columnLog.isEmpty()) {
            hp
                    .H3()
                    .__localize("_ title.importation.initlog")
                    ._H3();
            hp
                    .UL();
            for (SourceMessage sourceMessage : columnLog.getSourceMessageList()) {
                hp
                        .LI()
                        .SPAN(LogUtils.getClassName(sourceMessage.getCategory()))
                        .__localize(sourceMessage)
                        ._SPAN()
                        ._LI();
            }
            hp
                    ._UL();
        }
        LineLogs lineLogs = parseResult.getLineLogs();
        if (!lineLogs.isEmpty()) {
            hp
                    .H3()
                    .__localize("_ title.importation.lineerror")
                    ._H3();
            hp
                    .DL();
            for (LineLog lineLog : lineLogs) {
                hp
                        .DT()
                        .__append(lineLog.getLineNumber())
                        .__colon()
                        ._DT()
                        .DD()
                        .UL();
                for (LineMessage lineMessage : lineLog.getLineMessageList()) {
                    hp
                            .LI()
                            .__escape('[')
                            .__escape(lineMessage.getCategory())
                            .__escape(']')
                            .__space()
                            .__localize(lineMessage)
                            ._LI();
                }
                hp
                        ._UL()
                        ._DD();
            }
            hp
                    ._DL();
        }

        return true;
    }

    public static boolean printImportParseRows(HtmlPrinter hp, Map<String, String> storeMap) {
        String fieldValue = storeMap.getOrDefault(AbstractImportParseCommand.FIELDS_PARAMNAME, "");
        String currentParseType = getCurrentParseType(storeMap);
        String fieldOrigin = storeMap.getOrDefault(AbstractImportParseCommand.FIELDSORIGIN_PARAMNAME, AbstractImportParseCommand.FIRSTLINE_FIELDSORIGIN_PARAMVALUE);
        String currentCharset = storeMap.getOrDefault(AbstractImportParseCommand.CHARSET_PARAMNAME, "UTF-8");
        hp
                .__(Grid.choiceSetRow("_ label.importation.fields", () -> {
                    hp
                            .__(Grid.radioCell("_ label.importation.fieldsorigin_firstline", hp.name(AbstractImportParseCommand.FIELDSORIGIN_PARAMNAME).value(AbstractImportParseCommand.FIRSTLINE_FIELDSORIGIN_PARAMVALUE).checked(fieldOrigin)))
                            .__(Grid.radioCell("_ label.importation.fieldsorigin_input", hp.name(AbstractImportParseCommand.FIELDSORIGIN_PARAMNAME).value(AbstractImportParseCommand.INPUT_FIELDSORIGIN_PARAMVALUE).checked(fieldOrigin),
                                    () -> {
                                        hp
                                                .TEXTAREA(hp.name(AbstractImportParseCommand.FIELDS_PARAMNAME).cols(65).rows(3))
                                                .__escape(fieldValue, true)
                                                ._TEXTAREA();
                                    }));
                }))
                .__(Grid.choiceSetRow("_ label.importation.parsetype", () -> {
                    hp
                            .__(Grid.radioCell("_ label.importation.parsetype_sheetcopy", hp.name(InteractionConstants.PARSETYPE_PARAMNAME).value(TableParser.SHEETCOPY_PARSETYPE).checked(currentParseType)))
                            .__(Grid.radioCell("_ label.importation.parsetype_csv", hp.name(InteractionConstants.PARSETYPE_PARAMNAME).value(TableParser.CSV_PARSETYPE).checked(currentParseType),
                                    () -> {
                                        hp
                                                .__(Grid.START)
                                                .__(printCSVOptions(hp, storeMap))
                                                .__(Grid.END);
                                    }));

                }))
                .__(Grid.fileInputRow("_ label.importation.file", hp.name(AbstractImportParseCommand.FILE_PARAMNAME).size("45").classes("global-FileInput")))
                .DIV("global-DetailPanel grid-choice-DetailCell")
                .__(Grid.START)
                .__(Grid.selectRow("_ label.global.charset", hp.name(AbstractImportParseCommand.CHARSET_PARAMNAME).classes("global-CharsetSelect"),
                        () -> {
                            SortedMap<String, Charset> charsetMap = Charset.availableCharsets();
                            for (Map.Entry<String, Charset> entry : charsetMap.entrySet()) {
                                String canonicalName = entry.getKey();
                                Charset charset = entry.getValue();
                                hp
                                        .OPTION(canonicalName, currentCharset)
                                        .__escape(canonicalName);
                                Set<String> aliases = charset.aliases();
                                for (String alias : aliases) {
                                    hp
                                            .__escape(" ; ")
                                            .__escape(alias);
                                }
                                hp
                                        ._OPTION();
                            }
                        }))
                .__(Grid.END)
                ._DIV()
                .__(Grid.START_ROW)
                .SPAN("importation-Or grid-UniqueCell")
                .__localize("_ label.global.or")
                ._SPAN()
                .__(Grid.END_ROW)
                .__(Grid.textAreaBlockRow("_ label.importation.content", hp.name(AbstractImportParseCommand.CONTENT_PARAMNAME).classes("command-LargeInput").cols(100).rows(30)));
        return true;
    }


    private static boolean printCSVOptions(HtmlPrinter hp, Map<String, String> storeMap) {
        String currentDelimiter = StringUtils.charToString(getCurrentDelimiter(storeMap));
        String currentQuote = StringUtils.charToString(getCurrentQuote(storeMap));
        boolean escapedCSV = StringUtils.isTrue(storeMap.get(InteractionConstants.CSV_ESCAPED_PARAMNAME));
        hp
                .__(Grid.selectRow("_ label.importation.csv_delimiter", hp.name(InteractionConstants.CSV_DELIMITER_PARAMNAME), () -> {
                    for (String val : CsvParameters.getAvalaibleDelimiterArrayToString()) {
                        hp
                                .OPTION(val, currentDelimiter)
                                .__escape(val)
                                ._OPTION();
                    }
                }))
                .__(Grid.selectRow("_ label.importation.csv_quote", hp.name(InteractionConstants.CSV_QUOTE_PARAMNAME), () -> {
                    for (String val : CsvParameters.getAvalaibleQuoteArrayToString()) {
                        hp
                                .OPTION(val, currentQuote)
                                .__escape(val)
                                ._OPTION();
                    }
                }))
                .__(Grid.checkboxRow("_ label.importation.csv_escaped", hp.name(InteractionConstants.CSV_ESCAPED_PARAMNAME).value("1").checked(escapedCSV)));
        return true;
    }

    private static String getCurrentParseType(Map<String, String> storeMap) {
        String defaultParseType = TableParser.SHEETCOPY_PARSETYPE;
        String current = storeMap.get(InteractionConstants.PARSETYPE_PARAMNAME);
        if (current == null) {
            return defaultParseType;
        }
        try {
            return TableParser.checkParseType(current);
        } catch (IllegalArgumentException iae) {
            return defaultParseType;
        }
    }

    private static char getCurrentDelimiter(Map<String, String> storeMap) {
        char defaultChar = CsvParameters.getDefaultDelimiter();
        String current = storeMap.get(InteractionConstants.CSV_DELIMITER_PARAMNAME);
        if (current == null) {
            return defaultChar;
        }
        try {
            return StringUtils.stringToChar(current);
        } catch (IllegalArgumentException iae) {
            return defaultChar;
        }
    }

    private static char getCurrentQuote(Map<String, String> storeMap) {
        char defaultChar = CsvParameters.getDefaultQuote();
        String current = storeMap.get(InteractionConstants.CSV_QUOTE_PARAMNAME);
        if (current == null) {
            return defaultChar;
        }
        try {
            return StringUtils.stringToChar(current);
        } catch (IllegalArgumentException iae) {
            return defaultChar;
        }
    }

}
