package com.usai.apex;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;

import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class SearchListActivity extends Activity implements OnClickListener
{

	// String[] spin_valbool = { "True", "False" };
	LinearLayout			ll_list;
	String					user			= null;
	// String password = null;
	String					function_name	= null;
	HashMap<String, String>	hashMap			= new HashMap<String, String>();

	// private class Field
	// {
	// String name;
	// String value;
	// public Field(String n,String v)
	// {
	// name=n;
	// value=v;
	// }
	// }
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_list);

		user = ApexTrackingApplication.get_user();

		// password = ApexTrackingApplication.get_pass();
		function_name = getIntent().getStringExtra("function_name");

		setTitle(getIntent().getStringExtra("title"));

		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		Button btnok = (Button) findViewById(R.id.btnok);
		btnok.setOnClickListener(this);
		Button btncancel = (Button) findViewById(R.id.btncancel);
		btncancel.setOnClickListener(this);
		Button btnclear = (Button) findViewById(R.id.btn_clear);
		btnclear.setOnClickListener(this);
		if (savedInstanceState != null)
		{
			hashMap = (HashMap<String, String>) savedInstanceState
					.getSerializable("hashMap");
		}

	}

	@Override
	protected void onResume()
	{
		init();
		super.onResume();
	}

	void init()
	{
		// hashMap.clear();
		ll_list.removeAllViews();
		SQLiteDatabase db = dbUtil.OpenDB(this, null, true);
		Cursor cursor = 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);
		while (cursor.moveToNext())
		{
			final String aname = cursor.getString(0);
			String field_type = cursor.getString(1);
			final String name = cursor.getString(2);

			// hashMap.put(aname, field);

			if (field_type.equals("boolean"))
			{
				RelativeLayout spinneritem = (RelativeLayout) this
						.getLayoutInflater().inflate(
								R.layout.search_item_spinner, null);
				spinneritem.setTag("search_item_spinner");
				TextView tvname = (TextView) spinneritem
						.findViewById(R.id.aname);
				tvname.setText(aname);
				tvname.setTag(name);
				Spinner spinner_bool = (Spinner) spinneritem
						.findViewById(R.id.sp_bool);
				ArrayAdapter<CharSequence> adapter = ArrayAdapter
						.createFromResource(this, R.array.spinner_bool_val,
								android.R.layout.simple_spinner_item);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner_bool.setAdapter(adapter);
				String val = hashMap.get(name);
				if (val != null)
				{
					if (val.equals("true"))
						spinner_bool.setSelection(1);
					else if (val.equals("false"))
						spinner_bool.setSelection(2);
					else
						spinner_bool.setSelection(0);
				}

				spinner_bool
						.setOnItemSelectedListener(new OnItemSelectedListener()
						{

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int arg2, long arg3)
							{
								if (arg2 == 1)
									hashMap.put(name, "true");
								else if (arg2 == 2)
									hashMap.put(name, "false");

							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0)
							{

							}

						});
				// String val = hashMap.get(name);
				// if(val!=null)

				// switch_bool.setOnCheckedChangeListener(new
				// CompoundButton.OnCheckedChangeListener(){
				//
				// @Override
				// public void onCheckedChanged(CompoundButton buttonView,
				// boolean isChecked)
				// {
				// String val;
				// if(isChecked)
				// val="true";
				// else
				// val="false";
				// Field field = new Field(name,val);
				// field.name = name;
				// hashMap.put(aname,field);
				//
				// }
				//
				// });
				ll_list.addView(spinneritem);
			}
			else if (field_type.equals("time"))
			{

				RelativeLayout timeitem = (RelativeLayout) this
						.getLayoutInflater().inflate(
								R.layout.search_item_datepicker, null);
				timeitem.setTag("search_item_datepicker");
				TextView tvname = (TextView) timeitem.findViewById(R.id.aname);
				tvname.setText(aname);
				tvname.setTag(name);
				final EditText edit_from = (EditText) timeitem
						.findViewById(R.id.et_from);
				final EditText edit_to = (EditText) timeitem
						.findViewById(R.id.et_to);

				String val_from = hashMap.get(name + "_from");
				String val_to = hashMap.get(name + "_to");
				if (val_from != null)
				{
					edit_from.setText(val_from);
				}
				if (val_to != null)
					edit_to.setText(val_to);
				// edit_from.setInputType(InputType.TYPE_DATETIME_VARIATION_DATE
				// | InputType.TYPE_CLASS_DATETIME);
				final Calendar c = Calendar.getInstance();
				// int mYear =
				// int mMonth = c.get(Calendar.MONTH);
				// int mDay = c.get(Calendar.DAY_OF_MONTH);
				// final DatePickerDialog dialog =
				Button btn_clear_from = (Button) timeitem
						.findViewById(R.id.btn_clear_from);
				btn_clear_from.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						edit_from.setText("");
						hashMap.remove(name + "_from");

					}

				});
				Button btn_clear_to = (Button) timeitem
						.findViewById(R.id.btn_clear_to);
				btn_clear_to.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						edit_to.setText("");
						hashMap.remove(name + "_to");

					}

				});

				edit_from.setOnClickListener(new OnClickListener()
				{
					public void onClick(View v)
					{
						new DatePickerDialog(SearchListActivity.this,
								new DatePickerDialog.OnDateSetListener()
								{

									@Override
									public void onDateSet(DatePicker view,
											int year, int monthOfYear,
											int dayOfMonth)
									{
										edit_from
												.setText((monthOfYear + 1)
														+ "/" + dayOfMonth
														+ "/" + year);
										hashMap.put(name + "_from",
												(monthOfYear + 1) + "/"
														+ dayOfMonth + "/"
														+ year);

									}

								}, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
								c.get(Calendar.DAY_OF_MONTH)).show();

					}
				});

				edit_to.setOnClickListener(new OnClickListener()
				{
					public void onClick(View v)
					{
						new DatePickerDialog(SearchListActivity.this,
								new DatePickerDialog.OnDateSetListener()
								{

									@Override
									public void onDateSet(DatePicker view,
											int year, int monthOfYear,
											int dayOfMonth)
									{
										edit_to.setText((monthOfYear + 1) + "/"
												+ dayOfMonth + "/" + year);
										hashMap.put(name + "_to",
												(monthOfYear + 1) + "/"
														+ dayOfMonth + "/"
														+ year);

									}

								}, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
								c.get(Calendar.DAY_OF_MONTH)).show();

					}
				});

				ll_list.addView(timeitem);
			}
			else
			{
				RelativeLayout edititem = (RelativeLayout) this
						.getLayoutInflater().inflate(R.layout.search_item_edit,
								null);
				edititem.setTag("search_item_edit");
				TextView tvname = (TextView) edititem.findViewById(R.id.aname);
				tvname.setText(aname);
				tvname.setTag(name);

				AutoCompleteTextView edit = (AutoCompleteTextView) edititem
						.findViewById(R.id.edit_val);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_dropdown_item_1line,
						dbUtil.get_searchhistory(name));
				edit.setAdapter(adapter);

				String val = hashMap.get(name);
				if (val != null)
				{
					edit.setText(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)
					{
						String val = s.toString();
						val.trim();
						if (val.length() > 0)
						{

							hashMap.put(name, val);
						}
					}

				});
				if (field_type.equals("int"))
					edit.setInputType(InputType.TYPE_CLASS_NUMBER);

				ll_list.addView(edititem);
			}
		}
		dbUtil.CloseCursor(cursor);
		dbUtil.CloseDB(db);
	}

	@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_list, menu);
		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		outState.putSerializable("hashmap", hashMap);
		super.onSaveInstanceState(outState);
	}

	@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();

				boolean hascriterion = false;
				for (int i = 0; i < ll_list.getChildCount(); i++)
				{
					View item = ll_list.getChildAt(i);
					String tag = item.getTag().toString();
					TextView tv_aname = (TextView) item
							.findViewById(R.id.aname);
					String field_name = tv_aname.getTag().toString();
					String val = "";
					if (tag.equals("search_item_spinner"))
					{
						Spinner spinner_bool = (Spinner) item
								.findViewById(R.id.sp_bool);
						long sel = spinner_bool.getSelectedItemId();
						if (sel == 1)
							val = "true";
						else if (sel == 2)
							val = "false";
						else
							val = "";
						if (!TextUtils.isEmpty(val))
						{
							parms.putString(field_name, val);
							hascriterion = true;
						}
					}
					else if (tag.equals("search_item_edit"))
					{
						AutoCompleteTextView edit = (AutoCompleteTextView) item
								.findViewById(R.id.edit_val);
						val = edit.getText().toString().trim();
						if (!TextUtils.isEmpty(val))
						{
							parms.putString(field_name, val);
							hascriterion = true;

							dbUtil.savehistory(field_name, val);
						}
					}
					else if (tag.equals("search_item_datepicker"))
					{
						EditText et_from = (EditText) item
								.findViewById(R.id.et_from);
						String val_from = et_from.getText().toString().trim();
						EditText et_to = (EditText) item
								.findViewById(R.id.et_to);
						String val_to = et_to.getText().toString().trim();
						if (!TextUtils.isEmpty(val_from))
						{
							parms.putString(field_name + "_from", val_from);
							hascriterion = true;
						}
						if (!TextUtils.isEmpty(val_to))
						{
							parms.putString(field_name + "_to", val_to);
							hascriterion = true;
						}
					}

				}
				// String criterion = "";
				// if (hascriterion)
				// {
				// criterion = parms.toString();
				// }

				parms.putString("module_name", function_name);
				parms.putString("columns",
						dbUtil.get_fields(user, function_name));
				// Iterator<String> iter = hashMap.keySet().iterator();
				// while (iter.hasNext())
				// {
				// String aname = (String) iter.next();
				// Field field = (Field) hashMap.get(aname);
				// parms.putString(field.name, field.value);
				// }
				intent.putExtra("searchParms", parms);

				startActivity(intent);

				break;
			}
			case R.id.btncancel:
				finish();
				break;
			case R.id.btn_clear:
			{
				AlertDialog.Builder builder = new Builder(
						SearchListActivity.this);
				builder.setMessage("Click Reset button to reset");

				builder.setTitle("Confirm reset");

				builder.setPositiveButton("Reset", new Dialog.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						hashMap.clear();
						init();
						dialog.dismiss();

					}
				});

				builder.setNegativeButton("Cancel",
						new Dialog.OnClickListener()
						{

							@Override
							public void onClick(DialogInterface dialog,
									int which)
							{
								dialog.dismiss();
							}
						});

				builder.create().show();
			}
			default:
				break;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent intent = new Intent();
		switch (item.getItemId())
		{
			case R.id.action_custom_fields:
				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;
			case R.id.action_help:
				// Intent intent = new Intent();
				intent.setClass(this, HelpActivity.class);
				intent.putExtra("caller", "search");
				// // 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);
	}
}
