// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package routing.demo.convert;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class Util {
    public static String[] parseCSV(String line, char delim, char quote) {
        List<String> res = new ArrayList<String>();
        StringBuilder temp = new StringBuilder();
        boolean inquote = false;
        for(int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            if(c == delim) {
                if(inquote) {
                    temp.append(c);
                } else {
                    res.add(temp.toString());
                    temp = new StringBuilder();
                }
            } else if(c == quote) {
                if(i + 1 < line.length() && line.charAt(i + 1) == quote) {
                    temp.append(c);
                    i++;
                } else {
                    inquote = !inquote;
                }
            } else {
                temp.append(c);
            }
        }
        res.add(temp.toString());
        return res.toArray(new String[0]);
    }
    private static String NUMERIC = "\\d+(\\.\\d*)?";
    public static String formatValue(String value, char quote, QuoteHandling qh) {
        if(Pattern.matches(NUMERIC, value)) {
            return value;
        } else {
            switch(qh) {
                case DOUBLING:
                    return quote + value.replace("" + quote, "" + quote + quote) + quote;
                case ESCAPING:
                    return quote + value.replace("" + quote, "" + "\\" + quote) + quote;
                default:
                    throw new RuntimeException("Unknown quote handling");
            }
        }
    }
}
