package com.usai.apex;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MessageActivity extends ListActivity implements OnTouchListener
{
	SearchResult	searchresult	= new SearchResult();
	BaseAdapter		adapter			= null;

	private int		pointX, pointY, endX, endY;
	private int		position, newpos;
	private Button	curDel_btn;

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Intent intent = new Intent();
		switch (item.getItemId())
		{
			case R.id.action_deleteall:
			{
				AlertDialog.Builder builder = new Builder(this);
				builder.setMessage(getString(R.string.str_deletemessage));

				builder.setTitle(getString(R.string.str_confirmdelete));

				builder.setPositiveButton(getString(R.string.str_del),
						new Dialog.OnClickListener()
						{

							@Override
							public void onClick(DialogInterface dialog,
									int which)
							{
								SQLiteDatabase db = dbUtil.OpenDB(
										MessageActivity.this, null, false);
								db.execSQL("delete from push_message");
								Log.d("sql delete" + position,
										"delete from push_message where _id="
												+ (Long) searchresult.getData()
														.get(position)
														.get("_id"));

								dbUtil.CloseDB(db);
								dialog.dismiss();
								searchresult.getData().clear();// .remove(position);
								adapter.notifyDataSetChanged();
								NotificationManager nManager = (NotificationManager) 
										getSystemService(Context.NOTIFICATION_SERVICE);
								nManager.cancel(R.layout.activity_apex);
								ApexTrackingApplication.ncount=1;
							}
						});

				builder.setNegativeButton(getString(R.string.str_cancel),
						new Dialog.OnClickListener()
						{

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

				builder.create().show();

				break;
			}
			case R.id.action_markallread:
			{
				SQLiteDatabase db = dbUtil.OpenDB(
						MessageActivity.this, null, false);
				db.execSQL("update push_message set read = 1 where user = '"+ApexTrackingApplication.get_user()+"'");
				Log.d("sql delete" + position,
						"delete from push_message where _id="
								+ (Long) searchresult.getData()
										.get(position)
										.get("_id"));

				dbUtil.CloseDB(db);
				
				for(int i=0;i<searchresult.getData().size();i++)
				{
					searchresult.getData().get(i).put("read", (long) 1);

				}
//				searchresult.getData().clear();// .remove(position);
				adapter.notifyDataSetChanged();				
			}
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		switch (event.getAction())
		{
			case MotionEvent.ACTION_DOWN:
				System.out.println("====>>>>>>>>>>>>>>ACTION_DOWN"
						+ MotionEvent.ACTION_DOWN);
				// 手指按下,计算焦点位于ListView的那个条目
				pointX = (int) event.getX();
				pointY = (int) event.getY();
				// 备注1
				position = getListView().pointToPosition(pointX, pointY);
				if (curDel_btn != null)
				{
					curDel_btn.setVisibility(View.GONE);
				}
				break;
			case MotionEvent.ACTION_MOVE:

				break;
			case MotionEvent.ACTION_UP:
				System.out.println("====>>>>>>>>>>>>>>ACTION_UP"
						+ MotionEvent.ACTION_UP);
				endX = (int) event.getX();
				endY = (int) event.getY();
				newpos = getListView().pointToPosition(endX, endY);
				// 原本想着加上这个条件（newpos==position）是不是更精确些，
				// 经过实践发现，其实我们在滑动listView的列表的时候有时候更渴望有滑动就ok
				if (Math.abs(endX - pointX) > 100 && newpos == position
						&& Math.abs(endY - pointY) < 100)
				{
					// 获取到ListView第一个可见条目的position
					int firstVisiblePosition = getListView()
							.getFirstVisiblePosition();

					// --------------备注2
					View view = getListView().getChildAt(
							position - firstVisiblePosition);
					Button delbtn = (Button) view.findViewById(R.id.btn_del);
					delbtn.setVisibility(View.VISIBLE);
					curDel_btn = delbtn;
					delbtn.setOnClickListener(new View.OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							// TODO Auto-generated method stub

							SQLiteDatabase db = dbUtil.OpenDB(
									MessageActivity.this, null, false);
							db.execSQL("delete from push_message where _id="
									+ (Long) searchresult.getData()
											.get(position).get("_id"));
							Log.d("sql delete" + position,
									"delete from push_message where _id="
											+ (Long) searchresult.getData()
													.get(position).get("_id"));

							dbUtil.CloseDB(db);
							searchresult.getData().remove(position);
							adapter.notifyDataSetChanged();
						}
					});

				}
				break;

			default:
				break;
		}
		return false;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		SQLiteDatabase db = dbUtil.OpenDB(MessageActivity.this, null, false);
		db.execSQL("update push_message set read = 1 where _id="
				+ (Long) searchresult.getData().get(position).get("_id"));
		searchresult.getData().get(position).put("read", (long) 1);// .get("_id")
		dbUtil.CloseDB(db);
		adapter.notifyDataSetChanged();
		super.onListItemClick(l, v, position, id);

		// Log.i("FragmentList", "Item clicked: " + id);
		Intent intent = new Intent();
		intent.putExtra("s_id", (String) searchresult.getData().get(position)
				.get("s_id"));
		intent.putExtra("e_id", (String) searchresult.getData().get(position)
				.get("e_id"));
		intent.putExtra("msgcount", (Long) searchresult.getData().get(position)
				.get("msgcount"));

		intent.setClass(this, MessageDetailActivity.class);
		startActivity(intent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_list);
		adapter = new MessageAdapter(searchresult, this);

		getListView().setOnTouchListener(this);
		setListAdapter(adapter);

	}

	private class SearchResult
	{
		List<Map<String, Object>>	datalist	= new ArrayList<Map<String, Object>>();

		public int get_count()
		{
			return datalist.size();
		}

		public void add_records(Cursor c)
		{
			while (c.moveToNext())
			{
				long _id = c.getInt(0);
				String h_time = c.getString(1);
				long create_time = c.getLong(2);
				long read = c.getLong(3);
				String s_id = c.getString(4);
				String e_id = c.getString(5);
				long msgcount = c.getInt(6);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("_id", _id);
				map.put("h_time", h_time);
				map.put("create_time", create_time);
				map.put("read", read);
				map.put("s_id", s_id);
				map.put("e_id", e_id);
				map.put("msgcount", msgcount);

				datalist.add(map);
			}

		}

		public List<Map<String, Object>> getData()
		{

			return datalist;
		}
	}

	private class MessageAdapter extends BaseAdapter
	{
		private LayoutInflater	mInflater;	// 动态布局映射
											// private SearchResult result;

		// private Context context;
		// private int i = 0;
		public MessageAdapter(SearchResult result, Context context)
		{
			// this.result = result;
			this.mInflater = LayoutInflater.from(context);
			SQLiteDatabase db = dbUtil
					.OpenDB(MessageActivity.this, null, false);
			Cursor cursor = db.query("push_message",
					new String[] { "_id", "h_time", "create_time", "read",
							"s_id", "e_id", "msgcount" }, "user='"
							+ ApexTrackingApplication.get_user() + "'", null,
					null, null, "_id desc", null);

			result.add_records(cursor);
			dbUtil.CloseCursor(cursor);
			dbUtil.CloseDB(db);
			// this.result = result;
			// // this.context = context;
			// this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			convertView = mInflater.inflate(R.layout.message_list_item, null);// 根据布局文件实例化view

			TextView message = (TextView) convertView
					.findViewById(R.id.tv_message);// 找某个控件

			message.setText(getString(R.string.str_notification_text));// 给该控件设置数据(数据从集合类中来)
			TextView time = (TextView) convertView.findViewById(R.id.tv_time);
			time.setText(DateFormat.format(
					getString(R.string.time_format),
					(Long) searchresult.getData().get(position)
							.get("create_time")));
			if ((Long) searchresult.getData().get(position).get("read") == 0)
			{
				message.getPaint().setFakeBoldText(true);
				time.getPaint().setFakeBoldText(true);
				convertView.setBackgroundColor(Color.LTGRAY);
			}
			else
			{
				message.getPaint().setFakeBoldText(false);
				time.getPaint().setFakeBoldText(false);
				convertView.setBackgroundColor(Color.WHITE);
			}

			return convertView;
		}

		@Override
		public int getCount()
		{
			return searchresult.get_count();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}
	}

}
