package com.usai.apex;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Switch;
import android.widget.TextView;

public class SearchActivity extends ListActivity implements OnClickListener
{
	private SQLiteDatabase m_db = null;
	private Cursor m_cursor = null;
	String user = null;
	String password = null;
	String function_name = null;
	RecordsAdapter m_listadapter;
	private ListView m_ListView = null;
	HashMap<String, String> hashMap = new HashMap<String, String>();

	public class RecordsAdapter extends SimpleCursorAdapter
	{

		public RecordsAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to)
		{
			super(context, layout, c, from, to);
			// TODO Auto-generated constructor stub
		}

		// @Override
		// public View getView(int position, View convertView, ViewGroup parent)
		// {
		// // if(true)
		// // return super.getView(position, convertView, parent);
		// if(convertView==null)
		// convertView = LayoutInflater.from(getApplication()).inflate(
		// R.layout.search_lvitem_edit, null);
		// // holder = new ViewHolder();
		// // holder.textView = (TextView)convertView.findViewById(R.id.text);
		// // convertView.setTag(holder);
		// final int pos=position;
		// // convertView = LayoutInflater.from(getApplication()).inflate(
		// // R.layout.search_lvitem_edit, null);
		//
		// EditText editText = (EditText) convertView
		// .findViewById(R.id.edit_val);
		// // editText.setText(str);
		//
		// // 为editText设置TextChangedListener，每次改变的值设置到hashMap
		// // 我们要拿到里面的值根据position拿值
		// editText.addTextChangedListener(new TextWatcher()
		// {
		// @Override
		// public void onTextChanged(CharSequence s, int start,
		// int before, int count)
		// {
		//
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start,
		// int count, int after)
		// {
		//
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s)
		// {
		// // int a = position;
		// // 将editText中改变的值设置的HashMap中
		// hashMap.put(pos, s.toString());
		// }
		// });
		//
		// // // 如果hashMap不为空，就设置的editText
		// // if (hashMap.get(position) != null)
		// // {
		// // editText.setText(hashMap.get(position));
		// // }
		// return convertView;
		// }

		@Override
		public void bindView(View view, Context context, Cursor cursor)
		{
			String field_type = cursor.getString(1);
			final String name = cursor.getString(2);
			EditText edit = (EditText) view.findViewById(R.id.edit_val);
			edit.addTextChangedListener(new TextWatcher()
			{
				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count)
				{

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after)
				{

				}

				@Override
				public void afterTextChanged(Editable s)
				{
					// 将editText中改变的值设置的HashMap中
					String val = s.toString();
					val.trim();
					if (val.length() > 0)
						hashMap.put(name, val);
				}
			});
			Switch switch_bool = (Switch) view.findViewById(R.id.switch_bool);
			if (field_type.equals("boolean"))
			{
				edit.setVisibility(View.GONE);
				switch_bool.setVisibility(View.VISIBLE);
			}
			else
			{
				edit.setVisibility(View.VISIBLE);
				switch_bool.setVisibility(View.GONE);
				if (field_type.equals("time"))
				{
					edit.setInputType(InputType.TYPE_DATETIME_VARIATION_DATE
							| InputType.TYPE_CLASS_DATETIME);
				}
			}
			super.bindView(view, context, cursor);

			// TextView tvname = (TextView) view.findViewById(R.id.name);
			// TextView tvinfo = (TextView) view.findViewById(R.id.info);
			// String sname = cursor.getString(1);
			// int iburntype = cursor.getInt(2);
			// dbgUtil.Log(Log.INFO, "============>", "BURN TYPE =" +
			// iburntype);
			// if (sname == null || sname.equals(""))
			// tvname.setVisibility(TextView.GONE);
			// else
			// tvname.setVisibility(View.VISIBLE);
			// if (m_Activityinfo.NumberType != dbUtil.NUMBER_TYPE_WHITE
			// && iburntype >= 0)
			// {
			//
			// tvinfo.setText(m_arrBurntype[iburntype]);
			// tvinfo.setVisibility(View.VISIBLE);
			// }
			// else
			// {
			// tvinfo.setVisibility(View.GONE);
			// }

		}

	}

	@Override
	protected void onDestroy()
	{
		dbUtil.CloseDB(m_db);
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		user = getIntent().getStringExtra("user");
		password = getIntent().getStringExtra("password");
		function_name = getIntent().getStringExtra("function_name");
		setContentView(R.layout.activity_search);
		m_db = dbUtil.OpenDB(this, null, true);
		// m_TextView = (TextView) findViewById(R.id.summarytext);
		// m_TextView.setText(getString(m_Activityinfo.TextViewValue));
		m_ListView = (ListView) findViewById(android.R.id.list);
		m_cursor = m_db.query("fields_info", new String[] { "aname",
				"field_type", "name", "_id" }, "function_name='"
				+ function_name + "' and user='" + user + "' and behavior="
				+ Network.BEHAVIOR_SEARCH + " and show = 1", null, null, null,
				"priority , aname", null);
		startManagingCursor(m_cursor);
		m_listadapter = new RecordsAdapter(this,
		// Use a template that displays a text view
				R.layout.search_lvitem_edit,
				// Give the cursor to the list adatper
				m_cursor,
				// Map the NAME column in the people database to...
				new String[] { "aname", "field_type", "name" },
				// The "text1" view defined in the XML template
				new int[] { R.id.aliasName, R.id.tv_type });
		setListAdapter(m_listadapter);
		Button btnok = (Button) findViewById(R.id.btnok);
		btnok.setOnClickListener(this);
		Button btncancel = (Button) findViewById(R.id.btncancel);
		btncancel.setOnClickListener(this);
		// initlist();

		// m_ListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		// m_listadapter = new FieldsAdapter(this, data, resource, from, to);

		// m_listadapter = new RecordsAdapter(this,
		// // Use a template that displays a text view
		// m_iListItemID,
		// // Give the cursor to the list adatper
		// m_cursor,
		// // Map the NAME column in the people database to...
		// m_sDispFields,
		// // The "text1" view defined in the XML template
		// m_iViewIDs);

	}

	private void RefreshList()
	{
		// if (dbUtil.isRecordExist(m_db,
		// "user_numberlist","type = "+m_Activityinfo.NumberType))
		// {
		// m_TextView.setVisibility(ListView.INVISIBLE);
		// m_ListView.setVisibility(ListView.VISIBLE);
		//
		// }
		// else
		// {
		// m_TextView.setVisibility(ListView.VISIBLE);
		// m_ListView.setVisibility(ListView.INVISIBLE);
		// }
		hashMap.clear();
		m_cursor.requery();
	}

	// private void initlist()
	// {
	// m_ListView = (ListView) findViewById(android.R.id.list);
	// ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,
	// Object>>();
	// HashMap<String, Object> map = null;
	//
	// String[] strings = { "alias", "type", "name" };// Map的key集合数组
	// int[] ids = { R.id.aliasName, R.id.tv_type };// 对应布局文件的id
	// SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
	// R.layout.search_lvitem_edit, strings, ids);
	//
	// // listView1.setAdapter(simpleAdapter);//绑定适配器
	// setListAdapter(simpleAdapter);
	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, 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_SEARCH);
			startActivity(intent);
			break;

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

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btnok:
		{
			Intent intent = new Intent();
			intent.setClass(this, ResultActivity.class);
			intent.putExtra("user", user);
			intent.putExtra("password", password);
			intent.putExtra("function_name", function_name);
			Bundle parms = new Bundle();
			parms.putString("module_name",function_name);
			Iterator iter = hashMap.keySet().iterator();
			while (iter.hasNext())
			{
				String field = (String) iter.next();
				String val = (String) hashMap.get(field);
				parms.putString(field, val);
				// Cursor c = (Cursor) m_listadapter.getItem(key);
				Log.d("@@@@@@@@@", field + " : " + val);
			}
			intent.putExtra("searchParms", parms);

			startActivity(intent);

			break;
		}
		case R.id.btncancel:
			finish();
			break;
		default:
			break;
		}

	}

	// class FieldsAdapter extends SimpleAdapter
	// {
	//
	// public FieldsAdapter(Context context,
	// List<? extends Map<String, ?>> data, int resource,
	// String[] from, int[] to)
	// {
	// super(context, data, resource, from, to);
	// // TODO Auto-generated constructor stub
	// }
	//
	// }

}
