package se.kits.gakusei.util.csv;

import com.univocity.parsers.common.processor.RowListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import se.kits.gakusei.util.ParserFailureException;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CSV {

    /**
     * Parse a CSV file and return a map with its headers and rows.
     *
     * @param filePath
     * @param expectedNbrOdHeaders
     * @return Map
     */
    public static Map<String, List<String[]>> parse(String filePath, int expectedNbrOdHeaders) {

        CsvParserSettings settings = new CsvParserSettings();
        RowListProcessor rowProcessor = new RowListProcessor();

        settings.setLineSeparatorDetectionEnabled(true);
        settings.setRowProcessor(rowProcessor);
        settings.setHeaderExtractionEnabled(true);

        CsvParser parser = new CsvParser(settings);

        Map<String, List<String[]>> result = new HashMap<String, List<String[]>>();

        try {
            parser.parse(new FileReader(filePath));
        } catch(IOException e) {

            List err = new ArrayList<String>();
            err.add("CSV file could not be parsed");
            result.put("ERROR", err);

            return result;
        }

        List<String[]> headerList = new ArrayList<String[]>();

        String[] headers = rowProcessor.getHeaders();
        if (headers.length != expectedNbrOdHeaders) {
            throw new ParserFailureException("Unexpected number of headers" +
                    "\nExpected " + Integer.toString(expectedNbrOdHeaders) +
                    " but got " + Integer.toString(headers.length));
        }

        List<String[]> rows = rowProcessor.getRows();

        headerList.add(headers);

        result.put("HEADERS", headerList);
        result.put("ROWS", rows);

        return result;

    }

}

@@ -545,25 +545,25 @@
 expectedNbrO
-d
+f
 Headers%0A    
@@ -662,33 +662,33 @@
 int expectedNbrO
-d
+f
 Headers) %7B%0A%0A    
@@ -1535,33 +1535,33 @@
  != expectedNbrO
-d
+f
 Headers) %7B%0A     
@@ -1698,17 +1698,17 @@
 ctedNbrO
-d
+f
 Headers)

fix typo