package com.sunzee.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 可拖动控件
 */
@SuppressLint("AppCompatCustomView")
public class CustomView extends TextView {
    private int moveX;
    private int moveY;
    private InformationLocation informationLocation;
    private List<Float> arr = new ArrayList<>();


    public boolean isIsmove() {
        return ismove;
    }

    private boolean ismove;

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

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

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

    private static final String TAG = "CustomView";

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                moveX = x;
                moveY = y;
                ismove = false;
                Log.d(TAG, "ACTION_DOWN: "+ismove);
                break;
            case MotionEvent.ACTION_MOVE:
                //计算移动的距离
                int mOffsetX = x - moveX;
                int mOffsetY = y - moveY;
                Log.d(TAG, "mOffsetX: "+mOffsetX);
                Log.d(TAG, "mOffsetY: "+mOffsetY);
                if (mOffsetX>2||mOffsetY>2||mOffsetX<-2||mOffsetY<-2){
                    ismove = true;
                    Log.d(TAG, "ACTION_MOVE: "+ismove);
                }
                offsetLeftAndRight(mOffsetX);
                offsetTopAndBottom(mOffsetY);
                break;
            case MotionEvent.ACTION_UP:
                arr.add(getX());
                arr.add(getY());
                informationLocation.setInformationLocationListener(this, arr,ismove);
                break;
        }

        //调用layout方法来重新放置它的位置
        if (getX() >= 1422) {
            setX(1400);
        } else if (getX() <= 0) {
            setX(10);
        }
        if (getY() >= 770) {
            setY(760);
        } else if (getY() <= -1) {
            setY(10);
        }
        return true;
    }


    public void setInformationLocation(InformationLocation informationLocation) {
        this.informationLocation = informationLocation;
    }

    //提供控件的位置和id
    public interface InformationLocation {
        void setInformationLocationListener(View view, List<Float> list, boolean ismove);
    }
}
