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

import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.StringCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.Uint32Codec;
import com.jscape.inet.ssh.protocol.v2.messages.TerminalMode;
import com.jscape.util.io.ByteArrayInputStream;
import com.jscape.util.io.ByteArrayOutputStream;
import com.jscape.util.io.primitive.ByteCodec;

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

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

    private static final byte TTY_OP_END = 0;

    public static List<TerminalMode> readValue(InputStream in)
            throws IOException {
        byte[] data = StringCodec.readValue(in);
        ByteArrayInputStream buffer = new ByteArrayInputStream(data);
        List<TerminalMode> modes = new LinkedList<TerminalMode>();
        TerminalMode mode;
        while ((mode = readMode(buffer)) != null) {
            modes.add(mode);
        }

        return modes;
    }

    public static void writeValue(List<TerminalMode> value, OutputStream out)
            throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (TerminalMode mode : value) {
            writeMode(mode, buffer);
        }

        ByteCodec.writeValue(TTY_OP_END, buffer);
        StringCodec.writeValue(buffer.buffer(), 0, buffer.position(), out);
    }

    private static TerminalMode readMode(InputStream in)
            throws IOException {
        int opcode = ByteCodec.readValue(in) & 0xFF;

        if (opcode == TTY_OP_END) {
            return null;
        }

        int value = Uint32Codec.readValue(in);

        return new TerminalMode(opcode, value);
    }

    private static void writeMode(TerminalMode mode, OutputStream out)
            throws IOException {
        ByteCodec.writeValue((byte) mode.opcode, out);
        Uint32Codec.writeValue(mode.value, out);
    }

    private TerminalModesCodec() {
    }
}
