package com.jscape.inet.sftp.protocol.v3.marshaling;

import com.jscape.inet.sftp.protocol.messages.Message;
import com.jscape.inet.sftp.protocol.v3.messages.SshFxpInit;
import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.StringCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.primitive.Uint32Codec;
import com.jscape.util.io.DataCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Alex Usun
 */
public class SshFxpInitCodec
        implements DataCodec<Message> {

    @Override
    public Message read(InputStream in)
            throws IOException {
        int version = Uint32Codec.readValue(in);
        Map<String, String> extensionData = readExtensionData(in);

        return new SshFxpInit(version, extensionData);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        SshFxpInit message = (SshFxpInit) value;
        Uint32Codec.writeValue(message.version, out);
        writeExtensionData(message.extensionData, out);
    }

    private Map<String, String> readExtensionData(InputStream in)
            throws IOException {
        Map<String, String> extensionData = new LinkedHashMap<String, String>();

        while (in.available() > 0) {
            String name = StringCodec.readUtf8Value(in);
            String data = StringCodec.readUtf8Value(in);
            extensionData.put(name, data);
        }

        return extensionData;
    }

    private void writeExtensionData(Map<String, String> extensionData, OutputStream out)
            throws IOException {
        for (Map.Entry<String, String> entry : extensionData.entrySet()) {
            StringCodec.writeUtf8Value(entry.getKey(), out);
            StringCodec.writeUtf8Value(entry.getValue(), out);
        }
    }
}
