package com.atmob.keyboard_android.widget;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 长按检测容器
 */
public class LongTouchContainer extends FrameLayout {
    /**
     * 长按触发阈值，单位为毫秒
     */
    final int LONG_PRESS_DELAY = 100;

    private final Handler mMainHandler = new Handler();

    /**
     * 长按回调
     */
    private OnLongPressListener mOnLongPressListener;

    public LongTouchContainer(@NonNull Context context) {
        super(context);
    }

    public LongTouchContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LongTouchContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public LongTouchContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mMainHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 按下时，开始长按检测
                mMainHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 长按，持续回调
                        if (mOnLongPressListener != null) {
                            mOnLongPressListener.onLongPress();
                        }
                        mMainHandler.postDelayed(this, LONG_PRESS_DELAY);
                    }
                }, LONG_PRESS_DELAY);
                break;
            case MotionEvent.ACTION_UP:
                // 松开时移除回调
                mMainHandler.removeCallbacksAndMessages(null);
                // 松手那一刻，也回调一次
                if (mOnLongPressListener != null) {
                    mOnLongPressListener.onLongPress();
                }
                break;
        }
        return true; // 消费事件，避免点击冲突
    }

    public interface OnLongPressListener {
        void onLongPress();
    }

    /**
     * 设置长按回调
     */
    public void setOnLongPressListener(OnLongPressListener listener) {
        this.mOnLongPressListener = listener;
    }
}
