

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Vector;

import org.json.*;

public class CameraListRequestor {

	public static class CameraInfo {
		int objid;
		String type;
		String subtype;
		String name;
		String location;

		public String toString() {
			return "[" + objid + "] " + name;
		}
	}

	public static List<CameraInfo> getCameraList() throws Exception {

		String apiCallPath = "/api/call.php?function=getObjectList&type=camera&withAttributes=false";

		AppContext context = AppContext.getInstance();
		Session session = context.getSession();

		String urlStr = "http://" + context.getMasterHost() + apiCallPath;

		URL objlistURL = new URL(urlStr);
		URLConnection urlConnection = objlistURL.openConnection();
		urlConnection.setUseCaches(false);
		session.addSessionCookie(urlConnection);
		urlConnection.connect();

		int a;
		String jsonResponse = "";

		while ((a = urlConnection.getInputStream().read()) != -1) {
			jsonResponse += (char) a;
		}

		// JSONTokener(InputStream is) is apparently broken

		JSONObject json = new JSONObject(jsonResponse);

		List<CameraInfo> objList = new Vector<CameraInfo>();
		
		JSONArray jlist = json.getJSONArray("list");
		
		for (int i = 0; i < jlist.length(); i++) {
	
			CameraInfo obj = new CameraInfo();
			json = jlist.getJSONObject(i);
			obj.objid = json.getInt("obj");
			obj.name = json.getString("name");
			obj.type = json.getString("otype");
			obj.subtype = json.getString("subtype");
			obj.location = json.getString("location");
			objList.add(obj);
		}
		// }

		return objList;
	}

}
