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.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PropDocs extends ListActivity
{
	private static final String REMOTE_QUERY_SITE = "http://android.telkonet.com/dbpropdocs.php";
	
	private static final String PROPDOCS_ID = "DocID";
	private static final String PROPDOCS_TYPE = "Type";
	private static final String PROPDOCS_NAME = "DocName";
	private static final String PROPDOCS_PATH = "Path";
	private static final String PROPDOCS_EXT = "Extension";
	private static final String PROPDOCS_NOTES = "Notes";

	private static final int ADD_DOCUMENT_DIALOG = 0;

	private static final int ACTIVITY_ADDPHOTO = 0;
	
	private int propID = 0;
	private RowAdapter rowAdapter;
	
	private Context context;
	private ArrayList<ContentValues> notes = new ArrayList<ContentValues>(0);
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.propdocs);
		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();
		}
		
		
		DownloadThread dlt = new DownloadThread();
		dlt.execute();
		try
		{
			notes = dlt.get();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		rowAdapter = new RowAdapter(this, R.layout.propdocs_item, notes);
		setListAdapter(rowAdapter);

		ListView lv = getListView();
//		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() 
		{
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				// When clicked, do something
				Intent intent = null;
				String URIString = "http://admin.ethostream.com/sales/documents/Property" + Integer.toString(propID) + "/" + notes.get(position).getAsString(PROPDOCS_PATH);
				Log.i(this.toString(), Uri.parse(URIString).toString());
				intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URIString));
				startActivity(intent);
			}
		});
	}
	
	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 + "?ID=" + Integer.toString(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 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(PROPDOCS_ID, json_data.getString(PROPDOCS_ID));
				cv.put(PROPDOCS_TYPE, json_data.getString(PROPDOCS_TYPE));
				cv.put(PROPDOCS_NAME, json_data.getString(PROPDOCS_NAME));
				cv.put(PROPDOCS_PATH, json_data.getString(PROPDOCS_PATH));
				cv.put(PROPDOCS_EXT, json_data.getString(PROPDOCS_EXT));
				cv.put(PROPDOCS_NOTES, json_data.getString(PROPDOCS_NOTES));	
				list.add(cv);
			}
		}
		catch(Exception e)
		{
			Log.e(this.toString(), "FAILURE TO ACQUIRE REMOTE PROP INFO");
			e.printStackTrace();
			return new ArrayList<ContentValues>(0);
		}
		return list;
	}
	
	private class RowAdapter extends ArrayAdapter<ContentValues>
	{
		private ArrayList<ContentValues> list;
		
		public RowAdapter(Context context, int textViewResourceId, ArrayList<ContentValues> noteList) 
        {
                super(context, textViewResourceId, noteList);
                list = noteList;
        }
		@Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
        	View v = convertView;
        	if (v == null) 
        	{
        		LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        		v = vi.inflate(R.layout.propdocs_item, parent, false);
        	}
        	
        	ContentValues cv = list.get(position);

        	TextView type = (TextView) v.findViewById(R.id.propdocs_type);
        	TextView name = (TextView) v.findViewById(R.id.propdocs_name);
        	TextView notes = (TextView) v.findViewById(R.id.propdocs_notes);
        	       	
        	type.setText(cv.getAsString(PROPDOCS_TYPE));
        	name.setText(cv.getAsString(PROPDOCS_NAME));
        	notes.setText(cv.getAsString(PROPDOCS_NOTES));
        	
       	
        	return v;
        }
	}
}