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

import com.jscape.inet.scp.protocol.messages.Message;
import com.jscape.inet.scp.protocol.messages.TimeMessage;
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 TimeMessageCodec
        extends CodecBase {

    private static final int TIME_FACTOR = 1000;

    public Message read(InputStream in)
            throws IOException {
        try {
            String data = readLine(in);
            Scanner scanner = new Scanner(data).useDelimiter(" ");
            long modificationDate = scanner.nextLong() * TIME_FACTOR;
            scanner.next();
            long accessTime = scanner.nextLong() * TIME_FACTOR;

            return new TimeMessage(modificationDate, accessTime);
        } catch (Exception e) {
            throw IOTools.ioException(e);
        }
    }

    public void write(Message value, OutputStream out)
            throws IOException {
        TimeMessage message = (TimeMessage) value;
        String data = String.format("%s 0 %s 0", message.modificationDate / TIME_FACTOR, message.accessTime / TIME_FACTOR);
        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);

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