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.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
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.TextView;

public class Contact extends Activity
{
	private static final String CONTACTS_PARENTID = "ParentID";
	private static final String CONTACTS_PARENT_TYPE = "ParentType";
	private static final String CONTACTS_NAME = "ContactName";
	private static final String CONTACTS_ROLE = "ContactRole";
	private static final String CONTACTS_PHONE = "ContactPhone";
	private static final String CONTACTS_EXT = "ContactExten";
	private static final String CONTACTS_FAX = "ContactFax";
	private static final String CONTACTS_EMAIL = "ContactEmail";
	private static final String CONTACTS_CELL = "ContactCell";
	private static final String CONTACTS_NOTE = "ContactNote";
	private static final String CONTACTS_GROUP = "GroupName";
	
	private static final String REMOTE_QUERY_SITE = "http://android.telkonet.com/dbpropcontacts.php";
	
	private String contactID = null;
	private ContentValues contact = null;
	
	private Context context;
	
	public void onCreate(Bundle savedInstanceState) 
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.contact);
	    context = this;
	    
	    Bundle bundle = getIntent().getExtras();
	    contactID = bundle.getString("CONTACT");
	    
	    if ( contactID == null)
	    {
	    	Log.e(this.toString(), "FAILED TO RETRIEVE CONTACT INFO");
	    	finish();
	    }
	    
	    ArrayList<ContentValues> check = new ArrayList<ContentValues>();
	    DownloadThread dlt = new DownloadThread();
	    dlt.execute();
	    try
		{
	    	//TODO: add timeout and message
			check = dlt.get();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    if (!check.isEmpty())
	    {
	    	contact = check.get(0);
	    }
	    else
	    {
	    	//TODO: Display an error to the user
	    	//TODO: GLOBAL TODO: Check for attempts to access empty sets in other methods
	    	Log.e(this.toString(), "Failure to get contact data");
	    	return;
	    }
	    
	    TextView name = (TextView) findViewById(R.id.contact_name_value);
	    TextView role = (TextView) findViewById(R.id.contact_role_value);
	    TextView group = (TextView) findViewById(R.id.contact_group_value);
	    TextView cell = (TextView) findViewById(R.id.contact_cell_value);
	    TextView phone = (TextView) findViewById(R.id.contact_phone_value);
	    TextView extension = (TextView) findViewById(R.id.contact_extension_value);
	    TextView email = (TextView) findViewById(R.id.contact_email_value);
	    TextView fax = (TextView) findViewById(R.id.contact_fax_value);
	    TextView note = (TextView) findViewById(R.id.contact_note_value);
	    
	    name.setText(contact.getAsString(CONTACTS_NAME));
	    if (contact.getAsString(CONTACTS_ROLE).length() != 0)
	    {
	    	if (contact.getAsString(CONTACTS_PARENT_TYPE).equals("Group"))
	    	{
	    		group.setText(contact.getAsString(CONTACTS_GROUP));
	    	}
	    	else
	    	{
	    		group.setVisibility(android.view.View.GONE);
	    	}
	    	role.setText(contact.getAsString(CONTACTS_ROLE));
	    }
	    if (contact.getAsString(CONTACTS_CELL).length() != 0)
	    {
	    	findViewById(R.id.contact_cell_div).setBackgroundColor(android.graphics.Color.DKGRAY);
	    	cell.setText(contact.getAsString(CONTACTS_CELL));
	    }
	    else
	    {
	    	findViewById(R.id.contact_cell).setVisibility(android.view.View.GONE);
	    }
	    if (contact.getAsString(CONTACTS_PHONE).length() != 0)
	    {
	    	findViewById(R.id.contact_phone_div).setBackgroundColor(android.graphics.Color.DKGRAY);
	    	phone.setText(contact.getAsString(CONTACTS_PHONE));
	    	if (contact.getAsString(CONTACTS_EXT).length() != 0)
	    	{
	    		extension.setText(contact.getAsString(CONTACTS_EXT));
	    	}
	    	else
	    	{
	    		extension.setVisibility(android.view.ViewGroup.GONE);
	    		findViewById(R.id.contact_extension_label).setVisibility(android.view.View.GONE);
	    	}
	    }
	    else
	    {
	    	findViewById(R.id.contact_phone).setVisibility(android.view.View.GONE);
	    }
	    if (contact.getAsString(CONTACTS_EMAIL).length() != 0)
	    {
	    	findViewById(R.id.contact_email_div).setBackgroundColor(android.graphics.Color.DKGRAY);
	    	email.setText(contact.getAsString(CONTACTS_EMAIL));
	    }
	    else
	    {
	    	findViewById(R.id.contact_email).setVisibility(android.view.View.GONE);
	    }
	    if (contact.getAsString(CONTACTS_FAX).length() != 0)
	    {
	    	findViewById(R.id.contact_fax_div).setBackgroundColor(android.graphics.Color.DKGRAY);
	    	fax.setText(contact.getAsString(CONTACTS_FAX));
	    }
	    else
	    {
	    	findViewById(R.id.contact_fax).setVisibility(android.view.View.GONE);
	    }
	    if (contact.getAsString(CONTACTS_NOTE).length() != 0)
	    {
	    	findViewById(R.id.contact_note_div).setBackgroundColor(android.graphics.Color.DKGRAY);
	    	note.setText(contact.getAsString(CONTACTS_NOTE));
	    }
	    else
	    {
	    	findViewById(R.id.contact_note).setVisibility(android.view.View.GONE);
	    }

	}
	
	public void onClickCell(View v)
	{
		Intent intent = null;
		intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getAsString(CONTACTS_CELL)));
		startActivity(intent);
	}
	public void onClickPhone(View v)
	{
		Intent intent = null;
		if (contact.getAsString(CONTACTS_EXT).length() != 0)
		{
			intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getAsString(CONTACTS_PHONE) + ";" + contact.getAsString(CONTACTS_EXT)));
		}
		else
		{
			intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getAsString(CONTACTS_PHONE)));
		}
		startActivity(intent);
	}
	public void onClickEmail(View v)
	{
		Intent intent = null;
		intent = new Intent(Intent.ACTION_SEND);
		intent.setType("plain/text");
		intent.putExtra(Intent.EXTRA_EMAIL, new String[]{contact.getAsString(CONTACTS_EMAIL)});
		startActivity(Intent.createChooser(intent, "Send email with:"));
	}
	
	private class DownloadThread extends AsyncTask<Void, Void, ArrayList<ContentValues>> 
	{
		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 ArrayList<ContentValues> doInBackground(Void... params) 
		{
			return getRemotePropertyInfo();
		}
		@Override
		protected void onPostExecute(ArrayList<ContentValues> retValue) 
		{
			dialog.dismiss();
		}
	 }
	
	private ArrayList<ContentValues> getRemotePropertyInfo()
	{
		InputStream is = null;
		ArrayList<ContentValues> list = new ArrayList<ContentValues>();
		ArrayList<NameValuePair> queryResult = new ArrayList<NameValuePair>();
		StringBuilder sb = null;
		String result;
		
		//httpPost
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(REMOTE_QUERY_SITE + "?CONTACTID=" + contactID);
			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 ArrayList<ContentValues>(0);
		}
		//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 ArrayList<ContentValues>(0);
		}
		//parseJSON
		try
		{
			JSONArray jArray = new JSONArray(result);
			JSONObject json_data=null;
			for (int i = 0; i < jArray.length(); i++)
			{
				json_data = jArray.getJSONObject(i);
				ContentValues cv = new ContentValues();
				cv.put(CONTACTS_PARENTID, json_data.getString(CONTACTS_PARENTID));
				cv.put(CONTACTS_PARENT_TYPE, json_data.getString(CONTACTS_PARENT_TYPE));
				cv.put(CONTACTS_NAME, json_data.getString(CONTACTS_NAME));
				cv.put(CONTACTS_ROLE, json_data.getString(CONTACTS_ROLE));
				cv.put(CONTACTS_PHONE, json_data.getString(CONTACTS_PHONE));
				cv.put(CONTACTS_EXT, json_data.getString(CONTACTS_EXT));
				cv.put(CONTACTS_FAX, json_data.getString(CONTACTS_FAX));
				cv.put(CONTACTS_EMAIL, json_data.getString(CONTACTS_EMAIL));
				cv.put(CONTACTS_CELL, json_data.getString(CONTACTS_CELL));
				cv.put(CONTACTS_NOTE, json_data.getString(CONTACTS_NOTE));
				if (cv.getAsString(CONTACTS_PARENT_TYPE).equals("Group"))
				{
					cv.put(CONTACTS_GROUP, json_data.getString(CONTACTS_GROUP));
				}
				list.add(cv);
			}
		}
		catch(Exception e)
		{
			Log.e(this.toString(), "FAILURE TO ACQUIRE REMOTE PROP INFO");
			return new ArrayList<ContentValues>(0);
		}
		return list;
	}
}