package com.insidesecure.drm.android.reference.views.utils;

import android.view.MotionEvent;
import android.view.View;

public class SwipeDetector implements View.OnTouchListener{

    private float mActionDownX, mInitialActionDownX;
    private SwipeDetectorListener mSwipeDetectorListener;
    private static final int MIN_DISTANCE = 50;

    public SwipeDetector(final SwipeDetectorListener swipeDetectorListener) {
        mSwipeDetectorListener = swipeDetectorListener;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mActionDownX = motionEvent.getX();
                mInitialActionDownX = mActionDownX;
                break;
            case MotionEvent.ACTION_UP:
                if (Math.abs(motionEvent.getX() - mInitialActionDownX) < MIN_DISTANCE) {
                    //onClick action
                    mSwipeDetectorListener.onClick();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(motionEvent.getX() - mActionDownX) > MIN_DISTANCE) {
                    if (motionEvent.getX() > mActionDownX) {
                        // Left to Right swipe action
                        mSwipeDetectorListener.onSwipedFromLeftToRight();
                    } else {
                        // Right to left swipe action
                        mSwipeDetectorListener.onSwipedFromRightToLeft();
                    }
                    mActionDownX = motionEvent.getX();
                }
                break;
        }
        return true;
    }
}
