package com.usai.apex;

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

import com.usai.util.dbUtil;

import android.app.AlertDialog;
import android.app.Dialog;
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.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FavoritesFragment extends ListFragment 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 void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		adapter = new FavoritesAdapter(searchresult, getActivity());

		getListView().setOnTouchListener(this);
		setListAdapter(adapter);
		// this.getListView().setBackgroundColor(Color.WHITE);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{

		Intent intent = new Intent();
		// SQLiteDatabase db = dbUtil.OpenDB(getActivity(), null, false);
		// Cursor c = db.query("favorites", new String[]
		// {"params"},"_id="+searchresult.getData().get(position).get("_id"),null,
		// null, null, null);
		// if(c.moveToNext())
		// {
		String uri = (String) searchresult.getData().get(position)
				.get("params");
		try
		{
			intent = Intent.parseUri(uri, 0);

			startActivity(intent);
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}

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

		// private Context context;
		// private int i = 0;
		public FavoritesAdapter(SearchResult result, Context context)
		{
			// this.result = result;
			this.mInflater = LayoutInflater.from(context);
			SQLiteDatabase db = dbUtil.OpenDB(getActivity(), null, false);
			Cursor cursor = db.query("favorites", new String[] { "_id",
					"create_time", "name", "params" }, "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(searchresult.getData().get(position).get("name")
					.toString());// 给该控件设置数据(数据从集合类中来)
			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")));

			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;
		}
	}

	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);
				long create_time = c.getLong(1);
				String name = c.getString(2);
				String params = c.getString(3);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("_id", _id);

				map.put("create_time", create_time);
				map.put("name", name);

				map.put("params", params);

				datalist.add(map);
			}

		}

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

			return datalist;
		}
	}

	@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(getActivity(),
									null, false);
							db.execSQL("delete from favorites 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;
	}
}
