package com.emcaster.topics;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

public class MessageParserImpl implements MessageParser, Message {

	private final ByteBuffer _buffer;

	private String _topic;

	private byte[] _message;

	private DatagramPacket _packet;

	public MessageParserImpl(ByteBuffer buffer, DatagramPacket packet) {
		_buffer = buffer;
		_packet = packet;
	}

	public static boolean writeToBuffer(String topic, byte[] message, int offset,
			int length, ByteBuffer buffer) {
		byte[] topicBytes = topic.getBytes();
		int totalLength = topicBytes.length + length;
		if(totalLength > buffer.capacity()){
			throw new IllegalArgumentException("Message length: " + totalLength + " is greater than the capacity of the buffer: " + buffer.capacity());
		}
		if(buffer.position() + totalLength > buffer.capacity()){
			return false;
		}
		buffer.putInt(topicBytes.length);
		buffer.putInt(message.length);
		buffer.put(topicBytes);
		buffer.put(message, offset, length);
		return true;
	}

	public InetAddress getAddress(){
		return _packet.getAddress();
	}
	
	public int getPort(){
		return _packet.getPort();
	}
	
	public int getPosition(){
		return _buffer.position();
	}
	
	public Message copy(){
		return new MessageImpl(this);
	}
	
	public Message parseNextMessage() {
		int topicLength = _buffer.getInt();
		int msgLength = _buffer.getInt();
		byte[] topicBytes = new byte[topicLength];
		_message = new byte[msgLength];
		_buffer.get(topicBytes);
		_topic = new String(topicBytes);
		_buffer.get(_message);
		return this;
	}
	
	public String getTopic(){
		return _topic;
	}
	
	public byte[] getMessage(){
		return _message;
	}
}

@@ -185,24 +185,77 @@
 essage %7B%0D%0A%0D%0A
+%09public static String STRING_ENCODING = %22UTF-8%22;%0D%0A%09%0D%0A
 %09private fin
@@ -278,16 +278,16 @@
 uffer;%0D%0A
-
 %0D%0A%09priva
@@ -636,21 +636,19 @@
 = to
-pic.get
 Bytes(
+topic
 );%0D%0A
@@ -1120,32 +1120,212 @@
 rn true;%0D%0A%09%7D%0D%0A%0D%0A
+%09private static byte%5B%5D toBytes(String topic) %7B%0D%0A%09%09try%7B%0D%0A%09%09%09return topic.getBytes(STRING_ENCODING);%0D%0A%09%09%7Dcatch(Exception failed)%7B%0D%0A%09%09%09throw new RuntimeException(failed);%0D%0A%09%09%7D%0D%0A%09%7D%0D%0A%0D%0A
 %09public InetAddr
@@ -1806,20 +1806,18 @@
 topic = 
-new 
+to
 String(t
@@ -1871,27 +1871,214 @@
  this;%0D%0A%09%7D%0D%0A
-
 %09%0D%0A
+%09private String toString(byte%5B%5D topicBytes) %7B%0D%0A%09%09try%7B%0D%0A%09%09%09return new String(topicBytes, STRING_ENCODING);%0D%0A%09%09%7Dcatch(Exception failed)%7B%0D%0A%09%09%09throw new RuntimeException(failed);%0D%0A%09%09%7D%0D%0A%09%7D%0D%0A%0D%0A
 %09public Stri

add encoding.