package com.jscape.inet.ssh.protocol.v2.marshaling.primitive;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Alex Usun
 */
public class NameListCodec {

    private static final String DELIMITER = ",";

    public static List<String> readUsAsciiValue(InputStream in)
            throws IOException {
        String data = StringCodec.readUsAsciiValue(in);
        return parse(data);
    }

    public static List<String> readUtf8Value(InputStream in)
            throws IOException {
        String data = StringCodec.readUtf8Value(in);
        return parse(data);
    }

    public static void writeUsAsciiValue(List<String> value, OutputStream out)
            throws IOException {
        String data = format(value);
        StringCodec.writeUsAsciiValue(data, out);
    }

    public static void writeUtf8Value(List<String> value, OutputStream out)
            throws IOException {
        String data = format(value);
        StringCodec.writeUtf8Value(data, out);
    }

    public static List<String> parse(String data) {
        List<String> names = new LinkedList<String>();
        Scanner scanner = new Scanner(data).useDelimiter(DELIMITER);
        while (scanner.hasNext()) {
            String name = scanner.next().trim();
            names.add(name);
        }

        return names;
    }

    public static String format(List<String> value) {
        StringBuilder buffer = new StringBuilder();
        int i = 0;
        for (String name : value) {
            if (i++ > 0) {
                buffer.append(DELIMITER);
            }

            buffer.append(name);
        }
        return buffer.toString();
    }

    private NameListCodec() {
    }
}
