package com.usai.apex;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.usai.util.dbUtil;

import java.util.ArrayList;
import java.util.List;

//import android.content.DialogInterface.OnClickListener;

public class CustomizeFieldsActivity extends Activity implements
		OnClickListener
{
	//
	// @Override
	// protected void onCreate(Bundle savedInstanceState)
	// {
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.activity_customize_fields);
	// }
	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.customize_fields, menu);
		return true;
	}

	private static List<fieldedit> list = null;
	private DragListAdapter adapter = null;

	// public static List<String> groupKey = new ArrayList<String>();
	private List<fieldedit> showList = new ArrayList<fieldedit>();
	private List<fieldedit> hideList = new ArrayList<fieldedit>();
	private String user/* ,password */, function_name;
	private int behavior;

	public class fieldedit
	{
		public String name = null;
		public int _id = -1;

		public fieldedit(String str, int i)
		{
			name = str;
			_id = i;

		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		user = ApexTrackingApplication.get_user();
		// password = getIntent().getStringExtra("password");
		function_name = getIntent().getStringExtra("function_name");
		behavior = getIntent().getIntExtra("behavior", -1);
		setContentView(R.layout.activity_customize_fields);
		Button btnok = (Button) findViewById(R.id.btnok);
		btnok.setOnClickListener(this);
		Button btncancel = (Button) findViewById(R.id.btncancel);
		btncancel.setOnClickListener(this);

		initData();

		DragListView dragListView = (DragListView) findViewById(R.id.drag_list);
		adapter = new DragListAdapter(this, list);
		dragListView.setAdapter(adapter);
		
		SharedPreferences RunOnce = getSharedPreferences("Apex", 0);
		
		String vername;
		try
		{
			vername = getPackageManager().getPackageInfo(
					"com.usai.apex", 0).versionName;
			boolean bFirstRun = RunOnce.getBoolean(
					"FirstRun"+vername+"_fields", true);
			if(bFirstRun&&false)
			{
				SharedPreferences.Editor editor = RunOnce.edit();
				editor.putBoolean("FirstRun"+vername+"_fields", false);
				// Don't forget to commit your edits!!!
				editor.commit();
				Intent intent = new Intent();
				intent.setClass(this, HelpActivity.class);
				intent.putExtra("caller", "fields");
				startActivity(intent);
				
			}		
		}
		catch (NameNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.action_help:
			Intent intent = new Intent();
			intent.setClass(this, HelpActivity.class);
			intent.putExtra("caller", "fields");
//			// 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);
	}
	public void initData()
	{
		SQLiteDatabase db = dbUtil.OpenDB(this, null, false);
		Cursor cursor = db.query("fields_info", new String[] { "aname", "show",
				"_id" }, "function_name='" + function_name + "' and user='"
				+ user + "' and behavior=" + behavior, null, null, null,
				"priority , aname", null);
		while (cursor.moveToNext())
		{
			int show = cursor.getInt(1);
			if (show == 1)
				showList.add(new fieldedit(cursor.getString(0), cursor
						.getInt(2)));
			else
			{
				hideList.add(new fieldedit(cursor.getString(0), cursor
						.getInt(2)));

			}
		}
		// ��ݽ��
		list = new ArrayList<fieldedit>();

		// groupKey��ŵ��Ƿ����ǩ
		// groupKey.add("Display fields");
		// groupKey.add("Hide fields");

		// for (int i = 0; i < 5; i++)
		// {
		// navList.add("Aѡ��" + i);
		// }
		list.add(new fieldedit(getString(R.string.str_displayitem), -1));
		list.addAll(showList);

		// for (int i = 0; i <18; i++)
		// {
		// moreList.add("Bѡ��" + i);
		// }
		list.add(new fieldedit(getString(R.string.str_hideitem), -2));
		list.addAll(hideList);
		dbUtil.CloseCursor(cursor);
		dbUtil.CloseDB(db);
	}

	public static class DragListAdapter extends ArrayAdapter<fieldedit>
	{

		// private Context mContext;

		public DragListAdapter(Context context, List<fieldedit> objects)
		{
			super(context, 0, objects);
			// this.mContext = context;
		}

		public List<fieldedit> getList()
		{
			return list;
		}

		@Override
		public boolean isEnabled(int position)
		{
			if (getItem(position)._id < 0) // _id<0 means a group key
				return false;
			// if (groupKey.contains(getItem(position).name))
			// {
			// // ����Ƿ����ǩ������false������ѡ�У����ܵ��
			// return false;
			// }
			return super.isEnabled(position);
		}

		public int switchpos()
		{

			for (int i = 1; i < getCount(); i++)
			{
				if (getItem(i)._id < 0)
					return i;
			}
			return -1;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{

			View view = convertView;
			if (getItem(position)._id < 0) // _id<0 means a group key
			{
				view = LayoutInflater.from(getContext()).inflate(
						R.layout.drag_list_item_tag, null);
			}
			// if (groupKey.contains(getItem(position).name))
			// {
			// // ����Ƿ����ǩ���ͼ��ط����ǩ�Ĳ����ļ������������ļ���ʾЧ��ͬ
			// view = LayoutInflater.from(getContext()).inflate(
			// R.layout.drag_list_item_tag, null);
			// }
			else
			{
				// �������������ǩ���ͼ����������Ĳ����ļ�
				view = LayoutInflater.from(getContext()).inflate(
						R.layout.drag_list_item, null);
			}

			TextView textView = (TextView) view
					.findViewById(R.id.drag_list_item_text);
			textView.setText(getItem(position).name);

			return view;
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btnok:
		{
			// DragListView dragListView = (DragListView)
			// findViewById(R.id.drag_list);
			int count = 0;
			for (int i = 0; i < adapter.getCount(); i++)
			{
				fieldedit fe = adapter.getItem(i);
				if (fe._id == -2 || count > 0)
					break;
				if (fe._id >= 0)
					count++;

			}
			if (count == 0)
			{
				new AlertDialog.Builder(CustomizeFieldsActivity.this)
						.setIcon(android.R.drawable.ic_dialog_info)
						.setTitle("Error!")
						.setMessage("You must set at least 1 field visiable!")
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener()
								{
									public void onClick(DialogInterface dialog,
											int whichButton)
									{

										// finish();
										/* User clicked OK so do some stuff */
									}
								}).show();
				break;

			}

			int show = 1;
			SQLiteDatabase db = dbUtil.OpenDB(this, null, true);
			db.beginTransaction();
			for (int i = 0; i < adapter.getCount(); i++)
			{
				fieldedit fe = adapter.getItem(i);
				if (fe._id == -2)// hide group begin 
				{
					show = 0;
				}
				if (show == 1)
					db.execSQL("update fields_info set show=" + show
							+ " ,priority=" + i + " where _id=" + fe._id);
				else
					db.execSQL("update fields_info set show=" + show
							+ " where _id=" + fe._id);

			}
			db.setTransactionSuccessful();
			db.endTransaction();
			dbUtil.CloseDB(db);
			finish();
			// Log.d("fields",);
			break;
		}
		case R.id.btncancel:
			finish();
			break;
		default:
			break;
		}
		// TODO Auto-generated method stub

	}

}
