package com.kfzs.duanduan.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.RelativeLayout;

import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;

/**
 * Created by realicing on 2018/4/27.
 * realicing@sina.com
 */
public class DragRelativeLayout extends RelativeLayout {
    public DragRelativeLayout(Context context) {
        super(context);
    }

    public DragRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DragRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    float padding = getResources().getDimension(R.dimen.content_padding_10);
    float moveX;
    float moveY;
    float x;
    float y;

    static final int MIN_MOVE_DISTANCE = 10;
    private boolean isMove = false;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isMove = false;
                moveX = event.getX();
                moveY = event.getY();
                x = getX();
                y = getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float mx = getX() + event.getX() - moveX;
                float my = getY() + event.getY() - moveY;
                setX(mx);
                setY(my);
                isMove = Math.abs(mx-x) > MIN_MOVE_DISTANCE || Math.abs(my-y) > MIN_MOVE_DISTANCE;
                break;
            case MotionEvent.ACTION_UP:
                //纠正X
                if (getX() * 2 < G.WIDTH)
                    setX(padding);
                else
                    setX(G.WIDTH - padding - getWidth());
                //纠正Y
                if(getY() < padding){
                    setY(padding);
                } else {
                    ViewParent parent = getParent();
                    if (parent instanceof View) {
                        float maxY = ((View) parent).getHeight() - padding - getHeight();
                        if (getY() > maxY) {
                            setY(maxY);
                        }
                    }
                }

                if(!isMove){//没有移动过就点击
                    performClick();
                }
                isMove = false;
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        invalidate();
        return true;
    }
}
