package org.opensourcecurrency.hack;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.URI;
import org.apache.http.client.methods.HttpGet;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.opensourcecurrency.hack.RestTask;

public class Transactions extends ListActivity {    
	TextView selection;
	private static final String OAUTH_LISTPAYMENTS_ACTION = "org.opensourcecurrency.hack.OAUTH_LISTPAYMENTS";
	private static final String TAG = "OpenTransact";
	private ProgressDialog progress;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transactions);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
   		String provider = prefs.getString("assetProviderPref","");
		String access_token = prefs.getString("access_token","none");
        Log.d(TAG,"access_token : " + access_token);
       	String providerValues[];
       	providerValues = provider.split(" ");
    	final String asset_url = providerValues[4];
    	
    	try {
        	HttpGet transactionsRequest = new HttpGet(new URI(asset_url));
      		transactionsRequest.setHeader("Accept","application/json");
      		transactionsRequest.setHeader("Authorization","Bearer " + access_token);
        	RestTask task = new RestTask(this, OAUTH_LISTPAYMENTS_ACTION);
        	task.execute(transactionsRequest);
        	progress = ProgressDialog.show(this, "Fetching Transactions", "Waiting...", true);
    	} catch(Exception e) {
        	e.printStackTrace();    		
    	}
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
	 	//selection.setText(items[position]);
	}
	
    @Override
    public void onResume() {
      super.onResume();
      registerReceiver(receiver, new IntentFilter(OAUTH_LISTPAYMENTS_ACTION));
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	unregisterReceiver(receiver);
    }
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
    	private String counterparty(JSONObject transact,String emailAddress) {
    	    try {
          	    String to = transact.getString("to");
        	    String from = transact.getString("from");
                if(emailAddress==to) {
                	return from;
                } else {
                	return to;
                }
    	    } catch (Exception e) {
            	e.printStackTrace();    		    	    	
    	    }
    	    return "";
    	}
    	
    	@Override
    	public void onReceive(Context context, Intent intent) {
    		Log.d(TAG,"onReceive called (Transactions)!");
    		if(progress != null) {
    			progress.dismiss();
    		}
    		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    	    String emailAddress = prefs.getString("emailPref","");
    		String response = intent.getStringExtra(RestTask.HTTP_RESPONSE);
    		Log.d(TAG,"response(Transactions): "+response);

    		try {
              JSONArray transactions_response = new JSONArray(response);
          	  String[] items = new String[transactions_response.length()];
              for(int i=0;i<transactions_response.length();i++) {
            	  JSONObject transact = transactions_response.getJSONObject(i);
            	  String amount = transact.getString("amount");
            	  items[i] = amount + " " + counterparty(transact,emailAddress);
              }
              setListAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,items));
    		  selection=(TextView)findViewById(R.id.selection);
    		} catch (JSONException e) {
    		  e.printStackTrace();
    		}
    	}
    };
}

@@ -2726,13 +2726,20 @@
 ress
-==
+.equals(
 to)
+)
  %7B%0A 
@@ -2928,24 +2928,24 @@
 %0A    %09    %7D%0A
-
     %09    ret
@@ -2961,24 +2961,419 @@
    %09%7D%0A    %09%0A
+    %09private Boolean isPayer(JSONObject transact, String emailAddress) %7B%0A    %09%09try %7B%0A                if(emailAddress.equals(transact.getString(%22from%22))) %7B%0A                %09return true;%0A                %7D else %7B%0A                %09return false;%0A                %7D%0A    %09    %7D catch (Exception e) %7B%0A            %09e.printStackTrace();    %09%09    %09    %09%0A    %09    %7D%0A    %09    return false;    %09%09%0A    %09%7D%0A    %09%0A
     %09@Overri
@@ -4190,24 +4190,97 @@
 (%22amount%22);%0A
+            %09  String sign = isPayer(transact,emailAddress) ? %22-%22 : %22+%22;%0A
             
@@ -4292,16 +4292,23 @@
 ems%5Bi%5D =
+ sign +
  amount 

add sign of each transaction