package seng302.Networking.MessageEncoders;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

import static seng302.Networking.Utils.ByteConverter.intToBytes;
import static seng302.Networking.Utils.ByteConverter.longToBytes;
import static seng302.Networking.Utils.ByteConverter.shortToBytes;

/**
 * Encodes a XML file into a message of AC35 format
 */
public class XMLMessageEncoder {
    private byte[] messageVersionNumber;
    private short ackNumber;
    private long timeStamp;
    private byte[] xmlMsgSubType;
    private short sequenceNumber;
    private short xmlMsgLength;
    private String xmlMessage;

    public XMLMessageEncoder(short ackNumber, long timeStamp, int xmlMsgSubType, short sequenceNumber, short xmlMsgLength, String xmlMessage) {
        this.messageVersionNumber = intToBytes(1, 1);
        this.ackNumber = ackNumber;
        this.timeStamp = timeStamp;
        this.xmlMsgSubType = intToBytes(xmlMsgSubType, 1);
        this.sequenceNumber = sequenceNumber;
        this.xmlMsgLength = xmlMsgLength;
        this.xmlMessage = xmlMessage;
    }

    public byte[] encode() {
        byte[] messageBytes = xmlMessage.getBytes();
        if (messageBytes.length > this.xmlMsgLength) {
            //System.err.println("Xml message is to big");
            return null;
        }
        ByteBuffer tempOutputByteBuffer = ByteBuffer.allocate(14 + messageBytes.length);

        //ackNumber converted to bytes
        byte[] ackNumberBytes = shortToBytes(ackNumber, 2);

        //sequenceNumber converted to bytes
        byte[] sequenceNumberBytes = shortToBytes(sequenceNumber, 2);

        //xmlMsgLength converted to bytes
        byte[] xmlMsgLengthBytes = shortToBytes(xmlMsgLength, 2);


        tempOutputByteBuffer.put(messageVersionNumber);
        tempOutputByteBuffer.put(ackNumberBytes);
        tempOutputByteBuffer.put(longToBytes(timeStamp, 6));
        tempOutputByteBuffer.put(xmlMsgSubType);
        tempOutputByteBuffer.put(sequenceNumberBytes);
        tempOutputByteBuffer.put(xmlMsgLengthBytes);
        tempOutputByteBuffer.put(messageBytes);

        return tempOutputByteBuffer.array();
    }

}
