package it.integry.integrywmsnative.core.expansion;

import android.view.View;


/**
 * Implementation of {@link View.OnClickListener} that ignores subsequent clicks that happen too quickly after the first one.<br/>
 * To use this class, implement {@link #onSingleClick(View)} instead of {@link View.OnClickListener#onClick(View)}.
 */
public abstract class OnMultipleClickListener implements View.OnClickListener {
    private static final String TAG = OnMultipleClickListener.class.getSimpleName();

    private static final long MAX_DELAY_MS = 2000;

    private long mLastClickTime;
    private int mClickCounter = 0;

    @Override
    public final void onClick(View v) {
        long now = System.currentTimeMillis();
        long lastClickTime = mLastClickTime;
        mLastClickTime = now;

        if(now - lastClickTime > MAX_DELAY_MS) {
            mClickCounter = 0;
        }
        mClickCounter++;

        if (mClickCounter < 5) {
            return;
        }

        onSingleClick(v);
        mClickCounter = 0;
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    public abstract void onSingleClick(View v);

    /**
     * Wraps an {@link View.OnClickListener} into an {@link OnMultipleClickListener}.<br/>
     * The argument's {@link View.OnClickListener#onClick(View)} method will be called when a single click is registered.
     *
     * @param onClickListener The listener to wrap.
     * @return the wrapped listener.a
     */
    public static View.OnClickListener wrap(final View.OnClickListener onClickListener) {
        return new OnMultipleClickListener() {
            @Override
            public void onSingleClick(View v) {
                onClickListener.onClick(v);
            }
        };
    }
}
