package utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class CSVUtils {

    private static final char DEFAULT_SEPARATOR = ',';

    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }

    private static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());


    }

    static public void writeLines(Writer w, List<List<String>> data) throws IOException {
        for (List<String> line : data) {
            writeLine(w, line);
        }
    }

    public static ArrayList<String[]> readLines(Reader r) throws IOException {
        ArrayList<String[]> ret = new ArrayList<>();
        String line;
        String sep = String.valueOf(DEFAULT_SEPARATOR);
        try (BufferedReader br = new BufferedReader(r)) {
            while ((line = br.readLine()) != null) {
                String[] row = line.split(sep);
                ret.add(row);
            }
        }
        return ret;
    }

}
