/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.httprpc.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * CSV encoder.
 */
public class CSVEncoder {
    private List<String> keys;

    /**
     * Constructs a new CSV encoder.
     *
     * @param keys
     * The output column keys.
     */
    public CSVEncoder(List<String> keys) {
        if (keys == null) {
            throw new IllegalArgumentException();
        }

        this.keys = keys;
    }

    /**
     * Writes a sequence of values to an output stream.
     *
     * @param values
     * The values to encode.
     *
     * @param outputStream
     * The output stream to write to.
     *
     * @throws IOException
     * If an exception occurs.
     */
    public void writeValues(Iterable<? extends Map<String, ?>> values, OutputStream outputStream) throws IOException {
        writeValues(values, new OutputStreamWriter(outputStream, Charset.forName("ISO-8859-1")));
    }

    /**
     * Writes a sequence of values to a character stream.
     *
     * @param values
     * The values to encode.
     *
     * @param writer
     * The character stream to write to.
     *
     * @throws IOException
     * If an exception occurs.
     */
    public void writeValues(Iterable<? extends Map<String, ?>> values, Writer writer) throws IOException {
        writer = new BufferedWriter(writer);

        int i = 0;

        for (String key : keys) {
            if (key == null) {
                continue;
            }

            if (i > 0) {
                writer.append(',');
            }

            encodeValue(key, writer);

            i++;
        }

        writer.append("\r\n");

        for (Map<String, ?> map : values) {
            i = 0;

            for (String key : keys) {
                if (key == null) {
                    continue;
                }

                if (i > 0) {
                    writer.append(',');
                }

                Object value = valueAt(map, key);

                if (value != null) {
                    encodeValue(value, writer);
                }

                i++;
            }

            writer.append("\r\n");
        }

        writer.flush();
    }

    private void encodeValue(Object value, Writer writer) throws IOException {
        if (value instanceof CharSequence) {
            writer.write('"');
            writer.write(value.toString().replace("\"", "\"\""));
            writer.write('"');
        } else if (value instanceof Enum<?>) {
            encodeValue(((Enum<?>)value).ordinal(), writer);
        } else if (value instanceof Date) {
            encodeValue(((Date)value).getTime(), writer);
        } else {
            writer.append(value.toString());
        }
    }

    @SuppressWarnings("unchecked")
    private static <V> V valueAt(Map<String, ?> root, String path) {
        Object value = root;

        String[] components = path.split("\\.");

        for (int i = 0; i < components.length; i++) {
            String component = components[i];

            if (value instanceof Map<?, ?>) {
                value = ((Map<?, ?>)value).get(component);
            } else {
                value = null;

                break;
            }
        }

        return (V)value;
    }
}

@@ -877,16 +877,44 @@
 g%3E keys;
+%0A    private char delimiter;
 %0A%0A    /*
@@ -1052,32 +1052,314 @@
 String%3E keys) %7B%0A
+        this(keys, ',');%0A    %7D%0A%0A    /**%0A     * Constructs a new CSV encoder.%0A     *%0A     * @param keys%0A     * The output column keys.%0A     *%0A     * @param delimiter%0A     * The character to use as a field delimiter.%0A     */%0A    public CSVEncoder(List%3CString%3E keys, char delimiter) %7B%0A
         if (keys
@@ -1423,32 +1423,32 @@
 n();%0A        %7D%0A%0A
-
         this.key
@@ -1453,24 +1453,60 @@
 eys = keys;%0A
+        this.delimiter = delimiter;%0A
     %7D%0A%0A    /
@@ -2581,35 +2581,41 @@
   writer.append(
-','
+delimiter
 );%0A            %7D
@@ -2964,19 +2964,25 @@
 .append(
-','
+delimiter
 );%0A     

Add support for custom delimiter to CSVEncoder.