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

import com.jscape.inet.sftp.protocol.messages.Message;
import com.jscape.inet.sftp.protocol.v3.messages.FileAttributes;
import com.jscape.inet.sftp.protocol.v3.messages.FileOpenFlags;
import com.jscape.inet.sftp.protocol.v3.messages.SshFxpOpen;
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;

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

    @Override
    public Message read(InputStream in)
            throws IOException {
        int id = Uint32Codec.readValue(in);
        String filename = StringCodec.readUtf8Value(in);
        FileOpenFlags openFlags = FileOpenFlagsFormat.parse(Uint32Codec.readValue(in));
        FileAttributes attributes = FileAttributesCodec.readValue(in);

        return new SshFxpOpen(id, filename, openFlags, attributes);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        SshFxpOpen message = (SshFxpOpen) value;
        Uint32Codec.writeValue(message.id, out);
        StringCodec.writeUtf8Value(message.filename, out);
        Uint32Codec.writeValue(FileOpenFlagsFormat.format(message.openFlags), out);
        FileAttributesCodec.writeValue(message.attributes, out);
    }

}
