/* UtilLib - Copyright (c) 2007-2024 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 net.mapeadores.util.text.tableparser;

import java.lang.reflect.InvocationTargetException;
import net.mapeadores.util.exceptions.NestedClassLoaderException;
import net.mapeadores.util.text.StringUtils;


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

    public final static String CSV_PARSETYPE = "csv";
    public final static String SHEETCOPY_PARSETYPE = "sheetcopy";
    private static CsvParser csvParser = null;

    private TableParser() {
    }

    public static String[][] parse(String s, Parameters parameters) {
        if (parameters instanceof SheetCopyParameters) {
            return parseSheetCopy(s, (SheetCopyParameters) parameters);
        }
        if (parameters instanceof CsvParameters) {
            if (csvParser != null) {
                return csvParser.parse(s, (CsvParameters) parameters);
            }
            SimpleCsvParser scp = new SimpleCsvParser();
            return scp.parse(s, (CsvParameters) parameters);
        }
        throw new IllegalArgumentException("unknown TableParser.Parameters implementations = " + parameters.getClass().getName());
    }

    private static String[][] parseSheetCopy(String s, SheetCopyParameters parameters) {
        String[] lines = StringUtils.getLineTokens(s, StringUtils.NOTCLEAN);
        int length = lines.length;
        String[][] result = new String[length][];
        for (int i = 0; i < length; i++) {
            String line = lines[i];
            String[] tokens = StringUtils.getTokens(line, '\t', StringUtils.NOTCLEAN);
            result[i] = tokens;
        }
        return result;
    }

    public static boolean isCsvParserInit() {
        return (csvParser != null);
    }

    public static void initCsvParser(String className) {
        try {
            Class csvParserClass = Class.forName(className);
            csvParser = (CsvParser) csvParserClass.getDeclaredConstructor().newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException e) {
            throw new NestedClassLoaderException(e);
        }
    }

    public static String checkParseType(String parseType) {
        switch (parseType) {
            case CSV_PARSETYPE:
                return CSV_PARSETYPE;
            case SHEETCOPY_PARSETYPE:
                return SHEETCOPY_PARSETYPE;
            default:
                throw new IllegalArgumentException("Unknown parse type: " + parseType);
        }
    }


    public static interface Parameters {
    }

}
