package com.asafge.newsblurplus;

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

import android.content.Context;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;

public class APICall {
	
	public String CallbackUrl;
	public JSONObject Json;
	public AjaxStatus Status;
	private AjaxCallback<JSONObject> callback;
	private AQuery aquery;
	
	// Constructor
	public APICall(String url,  Context c) {
		aquery = new AQuery(c);
		// Create the callback object
		CallbackUrl = url;
		callback = new AjaxCallback<JSONObject>();
		callback.header("User-Agent", Prefs.USER_AGENT);
		String[] sessionID = Prefs.getSessionID(c);
		callback.cookie(sessionID[0], sessionID[1]);
		callback.url(CallbackUrl).type(JSONObject.class);
	}
	
	// Add a parameter to the call
	public void addParam(String key, Object value) {
		callback.param(key, value);
	}
	
	// Run synchronous HTTP request and check for valid response
	public boolean sync() {
		try {
			aquery.sync(callback);
			Json = callback.getResult();
			Status = callback.getStatus();
			if (Json == null)
				return false;
			if (Json.getString("authenticated") != "true") {
				// TODO: LoginActivity.logout();
				return false;
			}
			return (Status.getCode() == 200);
		}
		catch (JSONException e) {
			return false;
		}
	}
	
	// Run synchronous HTTP request, check valid response + successful operation 
	public boolean syncGetBool() {
		boolean result = true;
		try {
			result = (this.sync() && this.Json.getString("result").startsWith("ok"));
		} 
		catch (JSONException e) {
			result = false;
		}
		return result;		
	}
}

@@ -274,36 +274,8 @@
 %7B%0A%09%0A
-%09public String CallbackUrl;%0A
 %09pub
@@ -295,16 +295,16 @@
 t Json;%0A
+
 %09public 
@@ -390,16 +390,127 @@
 aquery;%0A
+%09private String callbackUrl;%0A%09%0A%09// Empty constructor%0A%09public APICall(Context c) %7B%0A%09%09aquery = new AQuery(c);%0A%09%7D%0A
 %09%0A%09// Co
@@ -621,17 +621,150 @@
 bject%0A%09%09
-C
+createCallback(url, c);%0A%09%7D%0A%0A%09// Create a callback object, before running sync%0A%09public void createCallback(String url, Context c) %7B%0A%09%09c
 allbackU
@@ -977,17 +977,17 @@
 ack.url(
-C
+c
 allbackU
@@ -1097,24 +1097,49 @@
 ct value) %7B%0A
+%09%09if (callback != null)%0A%09
 %09%09callback.p
@@ -1156,16 +1156,16 @@
 value);%0A
-
 %09%7D%0A%09%0A%09//
@@ -1223,16 +1223,16 @@
 esponse%0A
-
 %09public 
@@ -1248,16 +1248,57 @@
 ync() %7B%0A
+%09%09if (callback == null)%0A%09%09%09return false;%0A
 %09%09try %7B%0A

Allow to set APICall url after creating the object