package com.usai.apex;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;

import com.usai.util.Network;
import com.usai.util.dbUtil;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.R.integer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ResultActivity extends Activity
{
	String user = null;
	String password = null;
	String function_name = null;
	private SearchTask m_task = null;
	
	int sel = -1;

	Bundle searchParms = null;
	SearchResult searchresult = new SearchResult();

	HashMap<Integer, String> showfieldmap = new HashMap<Integer, String>();
	private TextView mStatusMessageView;
	// private View mSearchFormView;
	private View footview;
	private View mStatusView;

	// private class resultAdapter extends SimpleAdapter
	// {
	//
	//
	// }
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		user = getIntent().getStringExtra("user");
		password = getIntent().getStringExtra("password");
		function_name = getIntent().getStringExtra("function_name");
		searchParms = getIntent().getBundleExtra("searchParms");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_result);
		footview = findViewById(R.id.foot);
		// mSearchFormView = findViewById(R.id.search_form);
		Button btnnext = (Button) findViewById(R.id.btn_next);
		btnnext.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TextView tv_head = (TextView) findViewById(R.id.tv_head);

				searchresult.set_direction(1);
				if (searchresult.get_totalcount() == -1)
					requestdata(true);
				else
				{
					requestdata(false);
				}

			}
		});

		Button btnpre = (Button) findViewById(R.id.btn_pre);
		btnpre.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TextView tv_head = (TextView) findViewById(R.id.tv_head);
				searchresult.set_direction(-1);
				if (searchresult.get_totalcount() == -1)
					requestdata(true);
				else
				{
					requestdata(false);
				}

			}
		});
		mStatusView = findViewById(R.id.status);
		mStatusMessageView = (TextView) findViewById(R.id.status_message);
		initTable();
		requestdata(true);

	}

	private OnCreateContextMenuListener m_tableMenu = new OnCreateContextMenuListener()
	{

		@Override
		public void onCreateContextMenu(ContextMenu contextmenu, View view,
				ContextMenuInfo contextmenuinfo)
		{
			// TODO Auto-generated method stub
			// TableLayout tl = (TableLayout) view;
			//
			// TableRow tr = (TableRow) tl.getFocusedChild();
			// View v = (View) tl.getFocusedChild();
			contextmenu.add(Menu.NONE, 0, 0, "Detail");
			// contextmenu.add(Menu.NONE, 1, 1, "编辑");

		}

	};

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		// TODO Auto-generated method stub
		AdapterContextMenuInfo menuInfo;
//		menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		Log.d("table row select", sel+ "");
		// Cursor cursor = (Cursor) m_ListView
		// .getItemAtPosition(menuInfo.position);
		//
		// switch (item.getItemId())
		// {
		// case 0:
		// {// remove a record
		// int idx = cursor.getColumnIndex("number");
		// String strNumber = cursor.getString(idx);
		// String whereclause = "number = '" + strNumber + "'";
		// dbUtil.removeRecords(m_db, "user_numberlist", whereclause);
		// RefreshList();
		// // m_listadapter.notifyDataSetChanged();
		// // this.getListAdapter().notif
		// break;
		// }
		// // case 1:
		// // {
		// // //edit a record;
		// //
		// // int idx = cursor.getColumnIndex("_id");
		// // int id = cursor.getInt(idx);
		// //
		// // Intent intent = new Intent();
		// // intent.setClass(this, ActivityNumberListEdit.class);
		// // NumberEditInfo EditInfo = new NumberEditInfo();
		// // EditInfo.EditType = NumberEditInfo.TYPE_EDIT;
		// // EditInfo.EditTableName = m_Activityinfo.TableName;
		// //
		// // EditInfo.EditRecordID =id;
		// // if (m_Activityinfo.TableName == "user_blacklist")
		// // {
		// // // deal with black list;
		// // EditInfo.EditTable = NumberEditInfo.EDIT_TABLE_BLACK;
		// // EditInfo.CheckTableName = "user_whitelist";
		// // EditInfo.LabelTextID = R.string.label_AddBlack;
		// // EditInfo.NumberExistMoveID = R.string.phrase_numexist_white_mov;
		// // EditInfo.NumberExistID = R.string.phrase_numexist_blk;
		// // }
		// // else
		// // {
		// // // deal with white list;
		// // EditInfo.EditTable = NumberEditInfo.EDIT_TABLE_WHITE;
		// // EditInfo.CheckTableName = "user_blacklist";
		// // EditInfo.LabelTextID = R.string.label_AddWhite;
		// // EditInfo.NumberExistMoveID = R.string.phrase_numexist_blk_mov;
		// // EditInfo.NumberExistID = R.string.phrase_numexist_white;
		// // }
		// // intent.putExtra("ActivityInfo", EditInfo);
		// //
		// // startActivity(intent);
		// // break;
		// // }
		// }
		return super.onContextItemSelected(item);
	}

	// @Override
	// public void onCreateContextMenu(ContextMenu menu, View v,
	// ContextMenuInfo menuInfo)
	// {
	// // // TODO Auto-generated method stub
	// menu.add(Menu.NONE, 0, 0, "Detail");
	// // // contextmenu.add(Menu.NONE, 1, 1, "编辑");
	// super.onCreateContextMenu(menu, v, menuInfo);
	// }

	void initTable()
	{

		TableLayout tl = (TableLayout) findViewById(R.id.result_table);
		tl.setFocusable(true);
		tl.setOnCreateContextMenuListener(m_tableMenu);
		SQLiteDatabase db = dbUtil.OpenDB(this, null, false);
		Cursor cursor = db.query("fields_info", new String[] { "aname", "name",
				"_id" }, "function_name='" + function_name + "' and user='"
				+ user + "' and behavior=" + Network.BEHAVIOR_RESULT
				+ " and show = 1", null, null, null, "priority , aname", null);
		TableRow headerRow = (TableRow) findViewById(R.id.tr_header);
		int pos = 0;
		showfieldmap.clear();
		headerRow.removeAllViews();
		ArrayList<HashMap<String, String>> gridheader = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("key", "no.");
		gridheader.add(map);
		Button btn = new Button(this);
		btn.setBackgroundResource(R.drawable.tablehead);
		btn.setPadding(0, 0, 0, 0);
		btn.setText("No.");
		headerRow.addView(btn);
		while (cursor.moveToNext())
		{
			String aname = cursor.getString(0);
			Button btn1 = new Button(this);
			btn1.setBackgroundResource(R.drawable.tablehead);
			btn1.setText(aname);
			headerRow.addView(btn1);
			showfieldmap.put(pos, cursor.getString(1));

			map.put("key", "header");
			gridheader.add(map);
			pos++;
		}
		dbUtil.CloseCursor(cursor);
		dbUtil.CloseDB(db);

		// SimpleAdapter adapter = new SimpleAdapter(this,
		// gridheader,// 数据来源
		// R.layout.result_item,//XML实现
		// new String[] { "key" }, // 动态数组与ImageItem对应的子项
		// new int[] { R.id.tv_value });
		//
		// GridView gridview = (GridView) findViewById(R.id.grid_result);
		// gridview.setNumColumns(2);
		// gridview.setAdapter(adapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.result, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.action_custom_fields:
			Intent intent = new Intent();
			intent.setClass(this, CustomizeFieldsActivity.class);
			intent.putExtra("user", user);
			// intent.putExtra("password", password);
			intent.putExtra("function_name", function_name);
			intent.putExtra("behavior", Network.BEHAVIOR_RESULT);
			startActivity(intent);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void requestdata(boolean requestcount)
	{

		if (m_task != null)
		{
			return;
		}
		mStatusMessageView.setText("Loading");
		showProgress(true);
		m_task = new SearchTask();
		m_task.execute(requestcount);

	}

	private void showProgress(final boolean show)
	{
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
		{
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mStatusView.setVisibility(View.VISIBLE);
			mStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter()
					{
						@Override
						public void onAnimationEnd(Animator animation)
						{
							mStatusView.setVisibility(show ? View.VISIBLE
									: View.INVISIBLE);
						}
					});

			footview.setVisibility(View.VISIBLE);
			footview.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter()
					{
						@Override
						public void onAnimationEnd(Animator animation)
						{
							footview.setVisibility(show ? View.INVISIBLE
									: View.VISIBLE);
						}
					});
			// mSearchFormView.setVisibility(View.VISIBLE);
			// mSearchFormView.animate().setDuration(shortAnimTime)
			// .alpha(show ? 0 : 1)
			// .setListener(new AnimatorListenerAdapter()
			// {
			// @Override
			// public void onAnimationEnd(Animator animation)
			// {
			// mSearchFormView.setVisibility(show ? View.INVISIBLE
			// : View.VISIBLE);
			// }
			// });
		}
		else
		{
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mStatusView.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
			footview.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
			// mSearchFormView.setVisibility(show ? View.INVISIBLE :
			// View.VISIBLE);
		}
	}

	public class SearchTask extends AsyncTask<Boolean, Void, Boolean>
	{
		// int err_code = ERR_CODE_NONE;
		int errorcode;

		@Override
		protected Boolean doInBackground(Boolean... params)
		{

			if (!Network.NetworkIsAvailable())

			{
				errorcode = Network.RESULT_NET_NOTAVAILABLE;
				return false;
			}

			if (params[0])
			{
				int ret = Network.get_recordcount(user, password, searchParms);
				if (ret >= 0)
				{
					searchresult.put_totalcount(ret);
					if (ret == 0)
						return true;
				}
				else
				{
					errorcode = ret;
					return false;
				}
			}

			if (searchresult.get_direction() == -1)
				searchresult.set_offset(searchresult.get_offset() - 20);
			searchParms.putString("offset", searchresult.get_offset() + "");

			String jstr = Network.get_records(user, password, searchParms);
			if (jstr == null || jstr.length() <= 0)
			{
				// Log.d(TAG, "json is wrong");
				errorcode = Network.RESULT_NET_ERROR;
				return false;
			}

			JSONObject jsobj;
			//
			// array = new JSONArray(json);
			try
			{
				jsobj = new JSONObject(jstr);
				// if (searchresult.get_fieldscount() == 0)
				// {
				// JSONObject objfields = jsobj.getJSONObject("fields");
				// if (objfields != null)
				// searchresult.init_fields(objfields.toString());
				// }
				JSONObject objrecords = jsobj.getJSONObject("records");
				if (objrecords != null)
					searchresult.add_records(objrecords.toString());
				errorcode = Network.RESULT_TRUE;

				return true;

			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			errorcode = Network.RESULT_NET_ERROR;
			return false;

		}

		@Override
		protected void onPostExecute(final Boolean success)
		{
			Log.i("onPostExecute", "entry");
			m_task = null;
			showProgress(false);

			switch (errorcode)
			{
			case Network.RESULT_NET_NOTAVAILABLE:
			{
				Toast toast = Toast.makeText(getApplicationContext(),
						getText(R.string.msg_connection_none),
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			case Network.RESULT_NET_ERROR:
			{
				Toast toast = Toast.makeText(getApplicationContext(),
						getText(R.string.msg_net_error), Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			case Network.RESULT_ERROR:
			// case Network.RESULT_RESPONSE_NULL:
			{
				Toast toast = Toast.makeText(getApplicationContext(),
						getText(R.string.msg_net_resulterror),
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}

			default:
				break;
			}

			if (success)
			{

				// int loadcount = searchresult.get_count();
				int totalcount = searchresult.get_totalcount();
				TextView tv_head = (TextView) findViewById(R.id.head);
				if (totalcount == 0)
				{
					tv_head.setText("0 record found");
					return;
				}
				else
					tv_head.setText(/*
									 * loadcount + "/" +
									 */searchresult.get_totalcount()
							+ " records");
				TableLayout tl = (TableLayout) findViewById(R.id.result_table);

				int showcount = tl.getChildCount();
				tl.removeViews(1, tl.getChildCount() - 1);
				// int newcount = loadcount - showcount + 1;// +1 header row
				for (int i = 0; i < 10; i++)
				{

					TableRow recordRow = new TableRow(ResultActivity.this);
					recordRow
							.setOnLongClickListener(new View.OnLongClickListener()
							{

								@Override
								public boolean onLongClick(View v)
								{
									// TODO Auto-generated method stub
									// v.setBackgroundColor(Color.GRAY);
									// v.showContextMenu();
									// return true;
									TableRow tr = (TableRow)v;
									TextView tvno=(TextView)tr.getChildAt(0);
									String no = tvno.getText().toString();
									sel=Integer.parseInt(tvno.getText().toString());
									registerForContextMenu(v);
									openContextMenu(v);
									unregisterForContextMenu(v);
									return true;
								}
							});

					// registerForContextMenu(recordRow);
					// recordRow.setClickable(true);
					// registerForContextMenu(recordRow);
					// recordRow.setOnCreateContextMenuListener(m_tableMenu);
					// recordRow.SETSE

					HashMap<String, String> record = searchresult.get_record(i);
					TextView field = new TextView(ResultActivity.this);
					field.setBackgroundResource(R.drawable.tableitem);
					field.setText(searchresult.get_offset() - 10 + i + "");
					Log.d("offset=" + searchresult.get_offset(), "direction="
							+ searchresult.get_direction());
					field.setGravity(Gravity.CENTER);
					field.setPadding(10, 5, 10, 5);
					field.setTextSize(20);
					recordRow.addView(field);
					for (int j = 0; j < showfieldmap.size(); j++)
					{
						TextView field1 = new TextView(ResultActivity.this);
						String str = record.get(showfieldmap.get(j));
						field1.setBackgroundResource(R.drawable.tableitem);
						if (str.toLowerCase().trim().equals("null"))
							str = "";

						// field1.setBackgroundColor(0xFFFFFFFF);

						field1.setText(str);
						field1.setGravity(Gravity.CENTER);
						field1.setPadding(10, 5, 10, 5);
						field1.setTextSize(20);
						// field.setTextAppearance(ResultActivity.this,
						// android.R.attr.textAppearanceMedium);
						recordRow.addView(field1);
					}
					tl.addView(recordRow);
				}

				Button btnnext = (Button) findViewById(R.id.btn_next);

				Button btnpre = (Button) findViewById(R.id.btn_pre);
				if (searchresult.get_offset() <= 10)
					btnpre.setEnabled(false);
				else
				{
					btnpre.setEnabled(true);
				}
				if (searchresult.get_totalcount() - searchresult.get_offset() <= 10)
					btnnext.setEnabled(false);
				else
					btnnext.setEnabled(true);
				// // fill fake data
				// for(int i=0;i<10;i++)
				// {
				// TableRow recordRow = new TableRow(ResultActivity.this);
				// for(int j=0;j<showfieldmap.size();j++)
				// {
				// TextView field = new TextView(ResultActivity.this);
				// field.setText("fake data");
				// field.setGravity(Gravity.CENTER);
				// field.setTextAppearance(ResultActivity.this,android.R.attr.textAppearanceMedium);
				// recordRow.addView(field);
				// }
				// TableLayout tl=(TableLayout)findViewById(R.id.result_table);
				// tl.addView(recordRow);
				//
				// }

				// SharedPreferences.Editor editor = RunOnce.edit();
				// editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
				// false);
				// // Don't forget to commit your edits!!!
				// editor.commit();

				// Intent intent = new Intent();
				// intent.setClass(getActivity(), FunctionSelectActivity.class);
				// intent.putExtra("user", m_sUser);
				// intent.putExtra("password", m_sPassword);
				// startActivity(intent);
				// getActivity().finish();
			}
			else
			{
				// TextView tv_head = (TextView) findViewById(R.id.tv_head);
				// m_etPassword
				// .setError(getString(R.string.error_incorrect_password));
				// m_etPassword.requestFocus();
			}
		}

		@Override
		protected void onCancelled()
		{
			m_task = null;
			showProgress(false);
		}
	}

	private class SearchResult
	{
		int total_count = -1;
		int direction = 1;
		int offset = 0;
		// int count = 0;
		ArrayList<HashMap<String, String>> records = new ArrayList<HashMap<String, String>>();

		// ArrayList<field> fields = new ArrayList<field>();

		// public void init_fields(String jsonfields)
		// {
		// String TAG = "init_fields@ResultActivity.SearchResult";
		// Log.d(TAG, jsonfields);
		//
		// }

		public HashMap<String, String> get_record(int i)
		{
			return records.get(i);
		}

		public void add_records(String jsonstr)
		{
			try
			{
				records.clear();
				JSONObject objrecords = new JSONObject(jsonstr);
				for (int i = 0; i < objrecords.length(); i++)
				{
					offset++;
					JSONObject rec = objrecords.getJSONObject("record" + i);
					Iterator it = rec.keys();
					HashMap<String, String> record = new HashMap<String, String>();
					while (it.hasNext()) // loop for each function
					{
						String field_name = (String) it.next();
						String val = rec.getString(field_name);
						record.put(field_name, val);
					}
					records.add(record);

				}
				// searchresult.set_offset(offset);
				// Log.e("records count:",objrecords.length()+"");

			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String TAG = "init_fields@ResultActivity.SearchResult";
			Log.d(TAG, jsonstr);
		}

		public int get_totalcount()
		{
			return total_count;
		}

		public void put_totalcount(int c)
		{
			total_count = c;
		}

		public int get_offset()
		{
			return offset;
		}

		public int get_direction()
		{
			return direction;
		}

		public void set_offset(int i)
		{
			offset = i;

		}

		public void set_direction(int i)
		{
			direction = i;

		}
		// public int get_count()
		// {
		// return records.size();
		// }

		// public int get_fieldscount()
		// {
		// return fields.size();
		// }

		// private class record
		// {
		// HashMap<String,Object> values = ;
		//
		// }

		// private class field
		// {
		// String name = null;
		// String aliasname = null;
		// String type = null;
		//
		// public String get_name()
		// {
		// return name;
		// }
		//
		// public String get_aliasname()
		// {
		// return aliasname;
		// }
		//
		// public String get_type()
		// {
		// return type;
		// }
		//
		// }

	}
}
