package com.jscape.inet.scp.protocol.marshaling;

import com.jscape.inet.scp.protocol.messages.DirectoryMessage;
import com.jscape.inet.scp.protocol.messages.Message;
import com.jscape.util.IOTools;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author Alex Usun
 */
public class DirectoryMessageCodec
        extends CodecBase {

    public Message read(InputStream in)
            throws IOException {
        try {
            String data = readLine(in);
            Scanner scanner = new Scanner(data).useDelimiter(" ");
            String mode = scanner.next();
            scanner.next();
            String name = scanner.skip(" ").nextLine();

            return new DirectoryMessage(name, mode);
        } catch (Exception e) {
            throw IOTools.ioException(e);
        }
    }

    public void write(Message value, OutputStream out)
            throws IOException {
        DirectoryMessage message = (DirectoryMessage) value;
        String data = String.format("%s 0 %s", message.directoryMode, message.directoryName);
        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);

        out.write(bytes);
        out.write(EOL);
    }
}
