package org.stevewinfield.sunrise.communication;

import org.stevewinfield.sunrise.util.*;

public class MessageEvent {
	public String msg;
	public int pointer;
	public int id;
	
	public MessageEvent(String msg) {
		this.msg = msg;
		this.pointer = 2;
		this.id = B64Encoding.decode(this.msg.substring(0, 2));
	}
	
	private int getRemainingLength() {
		return this.msg.length() - this.pointer;
	}
	
	public String readString() {
		int length = B64Encoding.decode(this.msg.substring(this.pointer,  this.pointer + 2));
		this.pointer += 2;
		if (length > this.getRemainingLength()) length = this.getRemainingLength();
		String data = this.msg.substring(this.pointer,  this.pointer + length);
		this.pointer += length;
		return data;
	}
	
	public boolean readBoolean() {
		int x = WireEncoding.decode(this.msg.substring(this.pointer,  this.pointer + 1), 0);
		this.pointer++;
		return x == 1;
	}
	
	public int readInteger() {
		if (this.getRemainingLength() < 1) return 0;
		int length = 6;
		if (length > this.getRemainingLength()) length = this.getRemainingLength();
		String data = this.msg.substring(this.pointer,  this.pointer + length);
		int total = 0;
		int int_e = WireEncoding.decode(data, total);
		this.pointer += total;
		return int_e;
	}
}
