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

import com.jscape.inet.http.protocol.messages.Header;
import com.jscape.inet.http.protocol.messages.Message;
import com.jscape.inet.http.protocol.messages.ResponseMessage;
import com.jscape.util.IOTools;
import com.jscape.util.io.DataCodec;

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

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

    private static final int BUFFER_SIZE = 64 * 1024;

    public static ResponseMessage readValue(InputStream in)
            throws IOException {
        String version = LineCodec.readStringSpace(StandardCharsets.US_ASCII, in);
        String statusCodeData = LineCodec.readStringSpace(StandardCharsets.US_ASCII, in);
        int statusCode = Integer.parseInt(statusCodeData, 10);
        String reasonPhrase = LineCodec.readStringCRLF(StandardCharsets.US_ASCII, in);
        Header[] headers = HeadersCodec.readValue(in);

        return new ResponseMessage(version, statusCode, reasonPhrase, headers, in);
    }

    public static void writeValue(ResponseMessage value, OutputStream out)
            throws IOException {
        String statusLine = String.format("%s %s %s", value.protocolVersion, value.statusCode, value.reasonPhrase);
        LineCodec.writeStringCRLF(statusLine, StandardCharsets.US_ASCII, out);
        HeadersCodec.writeValue(value.headers, out);
        IOTools.copy(value.body, out, BUFFER_SIZE);
    }
    
    @Override
    public Message read(InputStream in)
            throws IOException {
        return readValue(in);
    }

    @Override
    public void write(Message value, OutputStream out)
            throws IOException {
        writeValue((ResponseMessage) value, out);
    }

}
