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

import com.jscape.inet.sftp.protocol.messages.Message;
import com.jscape.inet.sftp.protocol.v4.messages.FileAttributes;
import com.jscape.inet.sftp.protocol.v4.messages.NameEntry;
import com.jscape.inet.sftp.protocol.v4.messages.SshFxpName;
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 SshFxpNameCodec
        implements DataCodec<Message> {

    @Override
    public Message read(InputStream in)
            throws IOException {
        int id = Uint32Codec.readValue(in);
        NameEntry[] entries = readEntries(in);

        return new SshFxpName(id, entries);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        SshFxpName message = (SshFxpName) value;
        Uint32Codec.writeValue(message.id, out);
        writeEntries(message.entries, out);
    }

    private NameEntry[] readEntries(InputStream in)
            throws IOException {
        int count = Uint32Codec.readValue(in);
        NameEntry[] entries = new NameEntry[count];

        for (int i = 0; i < count; ++i) {
            String filename = StringCodec.readUtf8Value(in);
            FileAttributes attributes = FileAttributesCodec.readValue(in);
            entries[i] = new NameEntry(filename, attributes);
        }

        return entries;
    }

    private void writeEntries(NameEntry[] entries, OutputStream out)
            throws IOException {
        Uint32Codec.writeValue(entries.length, out);

        for (NameEntry entry : entries) {
            StringCodec.writeUtf8Value(entry.filename, out);
            FileAttributesCodec.writeValue(entry.attributes, out);
        }
    }

}
