package com.usai.redant.CommonEditor.EnumSelectAndSort;

import com.usai.redant.redantmobile.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class DragListView extends ListView
{

	private ImageView dragImageView;// ����ק�����ʵ����һ��ImageView
	private int dragSrcPosition;// ��ָ�϶���ԭʼ���б��е�λ��
	private int dragPosition;// ��ָ�϶���ʱ�򣬵�ǰ�϶������б��е�λ��

	private int dragPoint;// �ڵ�ǰ������е�λ��
	private int dragOffset;// ��ǰ��ͼ����Ļ�ľ���(����ֻʹ����y������)

	private WindowManager windowManager;// windows���ڿ�����
	private WindowManager.LayoutParams windowParams;// ���ڿ�����ק�����ʾ�Ĳ���

	private int scaledTouchSlop;// �жϻ�����һ������
	private int upScrollBounce;// �϶���ʱ�򣬿�ʼ���Ϲ����ı߽�
	private int downScrollBounce;// �϶���ʱ�򣬿�ʼ���¹����ı߽�

	public boolean canDrag = true;

	public DragListView(Context context) {
		this(context,null);
	}

	public DragListView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
	}

	public DragListView(Context context, AttributeSet attrs, int defStyleAttr) {

		super(context, attrs,defStyleAttr);
		scaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

		this.setOnItemClickListener(mItemClickListenter);

	}

	private int lastClickId = -1;
	private long lastClickTime;
	private OnItemClickListener mItemClickListenter = new OnItemClickListener()
	{
		public void onItemClick(AdapterView<?> parent, View v, int pos, long id)
		{
			DragListAdapter adapter = (DragListAdapter) ((ListView) parent)
					.getAdapter();

			if (adapter.isEnabled(pos) == false)// return if item is a group key
				return;

			Object dclickitem = getAdapter().getItem(pos);

			// �����˫��,1�����������ж�Ϊ˫��
			if (pos == lastClickId
					&& (Math.abs(lastClickTime - System.currentTimeMillis()) < 1000))
			{
				lastClickId = -1;
				lastClickTime = 0;
				if (pos < adapter.switchpos())
				{
					adapter.remove(dclickitem);
					adapter.insert(dclickitem, adapter.getCount());
				}
				else
				{
					adapter.remove(dclickitem);
					adapter.insert(dclickitem, 1);

				}
				adapter.notifyDataSetChanged();

			}
			else
			{
				lastClickId = pos;
				lastClickTime = System.currentTimeMillis();
			}
		}
	};

	// ����touch�¼�����ʵ���Ǽ�һ�����
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev)
	{
		if (ev.getAction() == MotionEvent.ACTION_DOWN)
		{
			int x = (int) ev.getX();
			int y = (int) ev.getY();

			dragSrcPosition = dragPosition = pointToPosition(x, y);
			if (dragPosition == AdapterView.INVALID_POSITION)
			{
				return super.onInterceptTouchEvent(ev);
			}

			ViewGroup itemView = (ViewGroup) getChildAt(dragPosition
					- getFirstVisiblePosition());
			dragPoint = y - itemView.getTop();
			dragOffset = (int) (ev.getRawY() - y);

			View dragger = itemView.findViewById(R.id.drag_list_item_image);
			if (dragger != null && x > dragger.getLeft() - 20)
			{
				//
				upScrollBounce = Math.min(y - scaledTouchSlop, getHeight() / 3);
				downScrollBounce = Math.max(y + scaledTouchSlop,
						getHeight() * 2 / 3);

				itemView.setDrawingCacheEnabled(true);
				Bitmap bm = Bitmap.createBitmap(itemView.getDrawingCache());
				itemView.setDrawingCacheEnabled(false);// 清除缓存，否则后面会看到
				startDrag(bm, y);
			}
			return false;
		}
		return super.onInterceptTouchEvent(ev);
	}

	private boolean moved = false;
	/**
	 * �����¼�
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev)
	{

		if (!canDrag) {

			return super.onTouchEvent(ev);
		}

		if (dragImageView != null && dragPosition != INVALID_POSITION)
		{
			int action = ev.getAction();
			switch (action)
			{
			case MotionEvent.ACTION_UP:
				if (moved) {
					int upY = (int) ev.getY();
					stopDrag();
					onDrop(upY);
					moved = false;
				}
				break;
			case MotionEvent.ACTION_MOVE:
				moved = true;
				int moveY = (int) ev.getY();
				onDrag(moveY);
				break;
			default:
				break;
			}
			return true;
		}
		// Ҳ������ѡ�е�Ч��
		return super.onTouchEvent(ev);
	}

	/**
	 * ׼���϶�����ʼ���϶����ͼ��
	 * 
	 * @param bm
	 * @param y
	 */
	public void startDrag(Bitmap bm, int y)
	{
		stopDrag();

		windowParams = new WindowManager.LayoutParams();
		windowParams.gravity = Gravity.TOP;
		windowParams.x = 0;
		windowParams.y = y - dragPoint + dragOffset;
		windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		windowParams.format = PixelFormat.TRANSLUCENT;
		windowParams.windowAnimations = 0;

		ImageView imageView = new ImageView(getContext());
		imageView.setImageBitmap(bm);
		windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(imageView, windowParams);
		dragImageView = imageView;
	}

	/**
	 * ֹͣ�϶���ȥ���϶����ͷ��
	 */
	public void stopDrag()
	{
		if (dragImageView != null)
		{
			windowManager.removeView(dragImageView);
			dragImageView = null;
		}
	}

	/**
	 * �϶�ִ�У���Move������ִ��
	 * 
	 * @param y
	 */
	public void onDrag(int y)
	{
		if (dragImageView != null)
		{
			windowParams.alpha = 0.8f;
			windowParams.y = y - dragPoint + dragOffset;
			windowManager.updateViewLayout(dragImageView, windowParams);
		}
		// Ϊ�˱��⻬�����ָ��ߵ�ʱ�򣬷���-1������
		int tempPosition = pointToPosition(0, y);
		if (tempPosition != INVALID_POSITION)
		{
			dragPosition = tempPosition;
		}

		// ����
		int scrollHeight = 0;
		if (y < upScrollBounce)
		{
			scrollHeight = 8;// �������Ϲ���8�����أ����������Ϲ����Ļ�
		}
		else
			if (y > downScrollBounce)
			{
				scrollHeight = -8;// �������¹���8�����أ������������Ϲ����Ļ�
			}

		if (scrollHeight != 0)
		{
			// ��������ķ���setSelectionFromTop()
			setSelectionFromTop(dragPosition,
					getChildAt(dragPosition - getFirstVisiblePosition())
							.getTop() + scrollHeight);
		}
	}

	/**
	 * �϶����µ�ʱ��
	 * 
	 * @param y
	 */
	public void onDrop(int y)
	{

		// Ϊ�˱��⻬�����ָ��ߵ�ʱ�򣬷���-1������
		int tempPosition = pointToPosition(0, y);
		if (tempPosition != INVALID_POSITION)
		{
			dragPosition = tempPosition;
		}

		// �����߽紦��
		if (y < getChildAt(1).getTop())
		{
			// �����ϱ߽�
			dragPosition = 1;
		}
		else
			if (y > getChildAt(getChildCount() - 1).getBottom())
			{
				// �����±߽�
				dragPosition = getAdapter().getCount() - 1;
			}

		// ��ݽ���
		if (dragPosition > 0 && dragPosition < getAdapter().getCount())
		{
			/* @SuppressWarnings("unchecked") */
			DragListAdapter adapter = (DragListAdapter) getAdapter();
			Object dragItem = adapter.getItem(dragSrcPosition);
			adapter.remove(dragItem);
			adapter.insert(dragItem, tempPosition); // dragSrcPosition 存在的问题：1 -> 0不能移动


			adapter.notifyDataSetChanged();;
		}

	}

	public static class DragListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 0;
		}

		@Override
		public Object getItem(int i) {
			return null;
		}

		@Override
		public long getItemId(int i) {
			return 0;
		}

		@Override
		public View getView(int i, View view, ViewGroup viewGroup) {
			return null;
		}

		public void insert(Object object,int position) {

		}

		public void remove(Object object) {

		}

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