package com.usai.apex;

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

import org.json.JSONException;
import org.json.JSONObject;


import com.usai.util.dbUtil;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
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.TextView;

public class HistoryFragment 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 HistoryAdapter(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();
		String uri = (String) searchresult.getData().get(position).get("params");
		String searchParms = (String) searchresult.getData().get(position).get("criterion");
		try
		{
//			Bundle bundle = new Bundle();
			intent = Intent.parseUri(uri, 0);
			Bundle parms = new Bundle();
//			parms.writeToParcel(parcel, flags)
			JSONObject obj = new JSONObject(searchParms);
			Iterator<?> it = obj.keys();
			while (it.hasNext())
			{

				String key = (String) it.next();
				parms.putString(key, obj.getString(key));

//					obj.put(key, searchParms.get(key).toString());



			}
			intent.putExtra("searchParms", parms);
//			obj.toString();
			
			intent.putExtra("columns",
					dbUtil.get_fields(ApexTrackingApplication.get_user(), (String) searchresult.getData().get(position).get("module_name")));
			startActivity(intent);
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		

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

		// private Context context;
		// private int i = 0;
		public HistoryAdapter(SearchResult result, Context context)
		{
			// this.result = result;
			this.mInflater = LayoutInflater.from(context);
			SQLiteDatabase db = dbUtil
					.OpenDB(getActivity(), null, false);
			Cursor cursor = db.query("history",
					new String[] { "_id", "create_time", "criterion",
							"params","module_name" ,"name"}, "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);// 找某个控件

			String name = (String) searchresult.getData().get(position).get("name");
			if(TextUtils.isEmpty(name))
			{
				name = "";
			}
			message.setText(name);// 给该控件设置数据(数据从集合类中来)
			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 criterion = c.getString(2);
				String params = c.getString(3);
				String module_name = c.getString(4);
				String name = c.getString(5);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("_id", _id);
				
				map.put("create_time", create_time);
				map.put("criterion", criterion);
				
				map.put("params", params);
				map.put("module_name", module_name);
				map.put("name", name);

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