
package org.appborg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class ABEvent {
	
	public long id;
	public String method;
	public String from;
	public JSONObject info;
	public JSONObject res;
	public JSONObject error;
	
	private ABComm comm;
	private boolean responded;
	
	public ABEvent(ABComm comm, String json) throws JSONException {
		
		this.comm = comm;
		responded = false;
		
		JSONObject jo = new JSONObject(json);
		id = jo.getLong("id");
		info = jo.getJSONObject("info");
		method = jo.getString("method");
		from = jo.getString("from");
		res = new JSONObject();
		error = null;
	}
	
	public void respond() {
		if ( ! responded) {
			try {
				comm.respond(this, res);
			} catch (JSONException e) {
				throw new RuntimeException(e);
			}
			responded = true;
		}
	}
	
	public void respondError(String message) {
		if ( ! responded) {
			JSONObject x = new JSONObject();
			try {
				x.put("message", x);
			} catch (JSONException e) {
				throw new RuntimeException(e);
			}
			respondError(x);
			responded = true;
		}
	}
	
	public void respondError(Exception exception) {
		if ( ! responded) {
			JSONObject x = new JSONObject();
			try {
				x.put("message", exception.toString());
				StackTraceElement[] st = exception.getStackTrace();
				JSONArray arr = new JSONArray();
				for (int i = 0; i < st.length; i++) {
					arr.put(st[i].toString());
				}
				x.put("stack_trace", arr);
			} catch (JSONException e) {
				throw new RuntimeException(e);
			}
			respondError(x);
			responded = true;
		}
	}
	
	public void respondError(JSONObject x) {
		error = x;
		if ( ! responded) {
			try {
				comm.respondError(this, x);
			} catch (JSONException e) {
				throw new RuntimeException(e);
			}
			responded = true;
		}
	}
}
