package seng302.Networking.MessageDecoders;

import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import static seng302.Networking.Utils.ByteConverter.bytesToLong;
import static seng302.Networking.Utils.ByteConverter.bytesToShort;

/**
 * Created by hba56 on 20/04/17.
 */
public class XMLMessageDecoder {
    private byte messageVersionNumber;
    private short ackNumber;
    private long timeStamp;
    private byte xmlMsgSubType;
    private short sequenceNumber;
    private short xmlMsgLength;
    private String xmlMessage;

    private byte[] bytes;

    public XMLMessageDecoder(byte[] bytes) {
        this.bytes = bytes;
    }

    public void decode(){
        byte[] ackNumberBytes = Arrays.copyOfRange(bytes, 1, 3);
        byte[] timeStampBytes = Arrays.copyOfRange(bytes, 3, 9);
        byte[] sequenceNumberBytes = Arrays.copyOfRange(bytes, 10, 12);
        byte[] xmlMsgLengthBytes = Arrays.copyOfRange(bytes, 12, 14);
        byte[] xmlMessagebytes = Arrays.copyOfRange(bytes, 14, bytes.length);

        this.xmlMsgSubType = bytes[9];
        this.messageVersionNumber = bytes[0];
        this.ackNumber = bytesToShort(ackNumberBytes);

        this.timeStamp = bytesToLong(timeStampBytes);

        this.sequenceNumber = bytesToShort(sequenceNumberBytes);
        this.xmlMsgLength = bytesToShort(xmlMsgLengthBytes);
        this.xmlMessage = new String(xmlMessagebytes);
    }

    public byte getMessageVersionNumber() {
        return messageVersionNumber;
    }

    public short getAckNumber() {
        return ackNumber;
    }

    public long getTimeStamp() {
        return timeStamp;
    }

    public byte getXmlMsgSubType() {
        return xmlMsgSubType;
    }

    public short getSequenceNumber() {
        return sequenceNumber;
    }

    public short getXmlMsgLength() {
        return xmlMsgLength;
    }

    /**
     * this will be used latter for the vis
     * @return xml string as inputsource
     */
    public InputStream getXmlMessageInputStream() {
        InputStream is =  new ByteArrayInputStream(xmlMessage.trim().getBytes(StandardCharsets.UTF_8));
//        InputSource is = new InputSource(new StringReader(xmlMessage.trim()));
        return is;
    }

}
