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 org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.TagHandler;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class PropNotes extends ListActivity
{
	private static final String REMOTE_QUERY_SITE = "http://android.telkonet.com/dbpropnotes.php";
	
	private static final String PROPNOTES_NOTEID = "NoteID";
	private static final String PROPNOTES_NOTETYPE = "NoteType";
	private static final String PROPNOTES_NOTEDATE = "NoteDate";
	private static final String PROPNOTES_NAME = "Name";
	private static final String PROPNOTES_NOTETEXT = "NoteText";
	
	private int propID = 0;
	private RowAdapter rowAdapter;
	private Context context;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.propnotes);
		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();
		ArrayList<ContentValues> notes = new ArrayList<ContentValues>(0);
		try
		{
			//TODO: set an appropriate timeout here
			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.propnotes_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

			}
		});
	}
	
	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(PROPNOTES_NOTEID,json_data.getString(PROPNOTES_NOTEID));
				cv.put(PROPNOTES_NOTETYPE, json_data.getString(PROPNOTES_NOTETYPE));
				cv.put(PROPNOTES_NOTEDATE, json_data.getString(PROPNOTES_NOTEDATE));
				cv.put(PROPNOTES_NAME, json_data.getString(PROPNOTES_NAME));
				cv.put(PROPNOTES_NOTETEXT, json_data.getString(PROPNOTES_NOTETEXT));	
				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.propnotes_item, parent, false);
        	}
        	
        	ContentValues cv = list.get(position);

        	TextView note = (TextView) v.findViewById(R.id.propnotes_note);
        	TextView type = (TextView) v.findViewById(R.id.propnotes_type);
        	TextView name = (TextView) v.findViewById(R.id.propnotes_name);
        	TextView date = (TextView) v.findViewById(R.id.propnotes_date);
        	
        	TableTagHandler tagHandler = new TableTagHandler();
        	Spanned htmlnote = Html.fromHtml(cv.getAsString(PROPNOTES_NOTETEXT), null, tagHandler);
        	note.setText(htmlnote);
        	
        	type.setText(cv.getAsString(PROPNOTES_NOTETYPE));
        	name.setText(cv.getAsString(PROPNOTES_NAME));
        	date.setText(cv.getAsString(PROPNOTES_NOTEDATE));
        	
        	return v;
        }
	}
	
	private class TableTagHandler implements TagHandler 
	{
		@Override
	    public void handleTag(boolean opening, String tag, Editable output,
	            XMLReader xmlReader) 
		{
	        if(tag.equalsIgnoreCase("tr")) 
	        {
	            tableRow(opening, output);
	        }
	        if(tag.equalsIgnoreCase("td"))
	        {
	        	tableColumn(opening, output);
	        }
	    }
		
		private void tableRow(boolean opening, Editable output)
		{
			if (opening)
			{
				//output.insert(output.length(), "\n------------------\n");
			}
			else
			{
				output.insert(output.length(), "\n---------------------------------\n");
			}
		}
		
		private void tableColumn(boolean opening, Editable output)
		{
			if (opening)
			{

				output.insert(output.length(), " | ");
			}
		}
	}


}
