package com.ethostream.ethoandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Matt Boelter - mboelter@ethostream.com
 * 
 * Activity for displaying information for a given property. The property is 
 * specified in a Bundle passed to this with the value of the ID of the property
 * on the remote SQL server. This class is also, regrettably, responsible for 
 * programmatically updating the TableLayout to display the information retrieved
 * about the property.
 * 
 * TODO: Formating, generalization of purpose. Add some buttons/navigation
 *
 */
public class PropInfo extends Activity
{
	private static final String REMOTE_QUERY_SITE = "http://android.telkonet.com/dbpropinfo.php";
	
	private static final String PROPINFO_PROPERTYNAME = "PropertyName";
	private static final String PROPINFO_CATEGORY = "Category";
	private static final String PROPINFO_ADDRESS1 = "Address1";
	private static final String PROPINFO_ADDRESS2 = "Address2";
	private static final String PROPINFO_CITY = "City";
	private static final String PROPINFO_STATE = "State";
	private static final String PROPINFO_ZIP = "Zip";
	private static final String PROPINFO_PHONE = "PropertyPhone";
	private static final String PROPINFO_FAX = "PropertyFax";
	
	private static final int ACTIVITY_APSTATUS = 0;
	
	private int propID = 0;
	
	private Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.propinfo);
		context = this;
		
		Bundle bundle = getIntent().getExtras();
		propID = Integer.parseInt(bundle.getString("ID"));
		if (propID < 1)
		{
			Log.e(this.toString(), "Invalid ID, quitting.");
			setResult(RESULT_CANCELED);
			finish();
		}
		
		JSONArray jArray = new JSONArray();
		DownloadThread dlt = new DownloadThread();
		dlt.execute();
		try
		{
			//TODO: add timeout and message
			jArray = dlt.get();
		} catch (InterruptedException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ExecutionException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		JSONObject json_data=null;
		try
		{
			//	Should only be one element, but we'll take the last one
			//	if there happens to be more
			for(int i=0;i<jArray.length();i++)
			{
				json_data = jArray.getJSONObject(i);
			}
		}
		catch (Exception e)
		{
			Log.e(this.toString(), "FAILURE TO RETRIEVE PROPERTY INFO");
			e.printStackTrace();
			setResult(RESULT_CANCELED);
			finish();
		}
		
		TextView propertyName = (TextView) findViewById(R.id.propinfo_name);
		TextView propertyCategory = (TextView) findViewById(R.id.propinfo_category);
		final TextView propertyAddress1 = (TextView) findViewById(R.id.propinfo_address1);
		final TextView propertyAddress2 = (TextView) findViewById(R.id.propinfo_address2);
		final TextView propertyCity = (TextView) findViewById(R.id.propinfo_city);
		final TextView propertyState = (TextView) findViewById(R.id.propinfo_state);
		final TextView propertyZip = (TextView) findViewById(R.id.propinfo_zip);
		final TextView propertyPhone = (TextView) findViewById(R.id.propinfo_phone);
		TextView propertyFax = (TextView) findViewById(R.id.propinfo_fax);
		
		
		try
		{
			propertyName.setText(json_data.getString(PROPINFO_PROPERTYNAME).trim());
			propertyCategory.setText("("
					+ json_data.getString(PROPINFO_CATEGORY).trim() + ")");
			propertyAddress1.setText(json_data.getString(PROPINFO_ADDRESS1).trim());
			propertyAddress2.setText(json_data.getString(PROPINFO_ADDRESS2).trim());
			if (json_data.getString(PROPINFO_ADDRESS2).length() == 0)
			{
				propertyAddress2.setVisibility(android.view.View.GONE);
			}
			propertyCity.setText(json_data.getString(PROPINFO_CITY).trim());
			propertyState.setText(json_data.getString(PROPINFO_STATE).trim());
			propertyZip.setText(json_data.getString(PROPINFO_ZIP).trim());
			propertyPhone.setText(json_data.getString(PROPINFO_PHONE).trim());
			propertyFax.setText(json_data.getString(PROPINFO_FAX).trim());
			
		} catch (JSONException e)
		{
			Log.e(this.toString(), "FAILURE TO ASSIGN PROP INFO");
			Log.e(this.toString(), "IGNORE AND CONTINUE");
		}
		
		Button apStatusButton = (Button) findViewById(R.id.propinfo_apstatus);
		apStatusButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				if (propID != 0)
				{
					switchView(ACTIVITY_APSTATUS, "ID", Integer.toString(propID));
				}
			}
		});
		Button callPropertyButton = (Button) findViewById(R.id.propinfo_callproperty);
		callPropertyButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				Intent intent = null;
				intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + propertyPhone.getText()));
				startActivity(intent);
			}
		});
		Button navigateButton = (Button) findViewById(R.id.propinfo_navigate);
		navigateButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				Intent intent = null;
				// Use address instead of LAT, LON as these values proved unreliable
				intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + propertyAddress1.getText() + " " + propertyAddress2.getText() + " " + propertyCity.getText() + ", " + propertyState.getText() + " " + propertyZip.getText()));
				startActivity(intent);
			}
		});
		
	}
	
	private class DownloadThread extends AsyncTask<Void, Void, JSONArray> 
	{
		final ProgressDialog dialog = new ProgressDialog(context);
		@Override
		protected void onPreExecute()
		{
			dialog.setTitle(R.string.activity_loading_label);
			dialog.setMessage(context.getString(R.string.activity_loading_message));
			dialog.show();
		}
		@Override
		protected JSONArray doInBackground(Void... params) 
		{
			return getRemotePropertyInfo();
		}
		@Override
		protected void onPostExecute(JSONArray retValue) 
		{
			dialog.dismiss();
		}
	 }
	
	/**
	 * Returns all of the data for a specified property, given by the remote 
	 * PHP SQL query. Note: the property is specified in a global variable in
	 * this class, but is passed in a bundle when this activity is launched, so
	 * this function can't be used outside of this class.
	 * 
	 * @return JSONArray
	 */
	private JSONArray getRemotePropertyInfo()
	{
		JSONArray jArray;
		InputStream is = null;
		ArrayList<NameValuePair> queryResult = new ArrayList<NameValuePair>();
		StringBuilder sb = null;
		String result;
		
		//httpPost
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(REMOTE_QUERY_SITE + "?ID=" + propID);
			httppost.setEntity(new UrlEncodedFormEntity(queryResult));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			Log.e(this.toString(), "Error in http connection"+e.toString());
			return new JSONArray();
		}
		//convertString
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line="0";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			Log.e("log_tag", "Error converting result "+e.toString());
			return new JSONArray();
		}
		//parseJSON
		try{
			jArray = new JSONArray(result);
		}
		catch(Exception e)
		{
			Log.e(this.toString(), "FAILURE TO ACQUIRE REMOTE PROP INFO");
			e.printStackTrace();
			return new JSONArray();
		}
		return jArray;
	}
	
	private void switchView(int ACTIVITY, String key, String value)
    {
    	switch(ACTIVITY)
    	{
    		case ACTIVITY_APSTATUS:
    		{
            	Intent i = new Intent(this, APStatus.class);
            	i.putExtra(key, value);
            	startActivityForResult(i, ACTIVITY_APSTATUS);
            	break;
    		}
    		default:
    		{
    			break;
    		}
    	}
    }
}
