package ua.naiksoftware.stomp.client;

import android.text.TextUtils;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ua.naiksoftware.stomp.StompHeader;

/**
 * Created by naik on 05.05.16.
 */
public class StompMessage {

    public static final String TERMINATE_MESSAGE_SYMBOL = "\u0000";

    private static final Pattern PATTERN_HEADER = Pattern.compile("([^:\\s]+):([^:\\s]+)");

    private final String mStompCommand;
    private final List<StompHeader> mStompHeaders;
    private final String mPayload;

    public StompMessage(String stompCommand, List<StompHeader> stompHeaders, String payload) {
        mStompCommand = stompCommand;
        mStompHeaders = stompHeaders;
        mPayload = payload;
    }

    public List<StompHeader> getStompHeaders() {
        return mStompHeaders;
    }

    public String getPayload() {
        return mPayload;
    }

    public String getStompCommand() {
        return mStompCommand;
    }

    public String findHeader(String key) {
        if (mStompHeaders == null) return null;
        for (StompHeader header : mStompHeaders) {
            if (header.getKey().equals(key)) return header.getValue();
        }
        return null;
    }

    public String compile() {
        StringBuilder builder = new StringBuilder();
        builder.append(mStompCommand).append('\n');
        for (StompHeader header : mStompHeaders) {
            builder.append(header.getKey()).append(':').append(header.getValue()).append('\n');
        }
        builder.append('\n');
        if (mPayload != null) {
            builder.append(mPayload).append("\n\n");
        }
        builder.append(TERMINATE_MESSAGE_SYMBOL);
        return builder.toString();
    }

    public static StompMessage from(String data) {
        if (TextUtils.isEmpty(data)) {
            return new StompMessage(StompCommand.UNKNOWN, null, data);
        }
        Scanner reader = new Scanner(new StringReader(data));
        reader.useDelimiter("\\n");
        String command = reader.next();
        List<StompHeader> headers = new ArrayList<>();

        while (reader.hasNext(PATTERN_HEADER)) {
            Matcher matcher = PATTERN_HEADER.matcher(reader.next());
            matcher.find();
            headers.add(new StompHeader(matcher.group(1), matcher.group(2)));
        }

        reader.skip("\\s");

        reader.useDelimiter(TERMINATE_MESSAGE_SYMBOL);
        String payload = reader.hasNext() ? reader.next() : null;

        return new StompMessage(command, headers, payload);
    }
}

@@ -1891,25 +1891,43 @@
     if (
-TextUtils
+data == null %7C%7C data.trim()
 .isEmpty
@@ -1927,20 +1927,16 @@
 isEmpty(
-data
 )) %7B%0A   

Fix parse empty stomp message 2