package com.bortbort.arduino.FiloFirmata.Parser.Builders;

import com.bortbort.arduino.FiloFirmata.Messages.Message;
import com.bortbort.arduino.FiloFirmata.Messages.SysexCapabilityResponseMessage;
import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes;
import com.bortbort.arduino.FiloFirmata.Parser.SysexMessageBuilder;
import com.bortbort.helpers.DataTypeHelpers;

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

/**
 * Created by chuck on 1/14/2016.
 */
public class SysexCapabilityResponseBuilder extends SysexMessageBuilder {

    public SysexCapabilityResponseBuilder() {
        super(SysexCommandBytes.CAPABILITY_RESPONSE);
    }

    @Override
    public Message buildMessage(byte[] messageBody) {
        ArrayList<byte[]> pinCapabilityBytes = new ArrayList<>();
        ArrayList<byte[]> pinMessages = splitPinMessages(messageBody);

        for (byte[] pinMessage : pinMessages) {
            //  This response is padded with extra bytes that we don't really care about right now in a cadence of
            //    every other byte. Skip over every other byte.
            byte[] capabilityBytes = new byte[pinMessage.length / 2];
            int currentByteIndex = 0;
            for (int x = 0; x < pinMessage.length / 2; x++) {
                capabilityBytes[x] = pinMessage[currentByteIndex];
                currentByteIndex += 2;
            }

            pinCapabilityBytes.add(capabilityBytes);
        }

        return new SysexCapabilityResponseMessage(pinCapabilityBytes);
    }

    private ArrayList<byte[]> splitPinMessages (byte[] messageBody) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(30);
        ArrayList<byte[]> pinCapabilities = new ArrayList<>();
        int bodySize = 0;
        for (byte bodyChunk : messageBody) {
            if (bodyChunk == 0x7f) {
                byte[] pinMessageBody = Arrays.copyOf(byteBuffer.array(), bodySize);
                pinCapabilities.add(pinMessageBody);
                byteBuffer.clear();
                bodySize = 0;
            }
            else {
                byteBuffer.put(bodyChunk);
                bodySize++;
            }
        }
        return pinCapabilities;
    }
}

@@ -102,32 +102,98 @@
 ssages.Message;%0A
+import com.bortbort.arduino.FiloFirmata.Messages.PinCapabilities;%0A
 import com.bortb
@@ -1671,32 +1671,126 @@
  messageBody) %7B%0A
+        // Arbitrary buffer size. Each capability has an extra potentially used byte with it.%0A
         ByteBuff
@@ -1829,10 +1829,43 @@
 ate(
-30
+PinCapabilities.values().length * 2
 );%0A 
@@ -1930,34 +1930,8 @@
 ();%0A
-        int bodySize = 0;%0A
     
@@ -2083,23 +2083,36 @@
 ray(), b
-odySize
+yteBuffer.position()
 );%0A     
@@ -2199,38 +2199,8 @@
 ();%0A
-                bodySize = 0;%0A
     
@@ -2228,16 +2228,16 @@
  else %7B%0A
+
         
@@ -2275,36 +2275,8 @@
 k);%0A
-                bodySize++;%0A
     

Clean up splitPinMessages a bit