package com.cooleshow.student.widgets.helper;

import android.os.Handler;
import android.os.Looper;

/**
 * Author by pq, Date on 2022/4/11.
 */
public class LiveRoomAddLikeHelper {
    private volatile static LiveRoomAddLikeHelper mHelper;
    // 两次点击按钮之间的点击间隔不能少于200毫秒
    private static final int MIN_CLICK_DELAY_TIME = 200;
    private static Handler sHandler = new Handler(Looper.getMainLooper());

    private LiveRoomAddLikeHelper() {

    }

    public static LiveRoomAddLikeHelper getInstance() {
        if (mHelper == null) {
            synchronized (LiveRoomAddLikeHelper.class) {
                if (mHelper == null) {
                    mHelper = new LiveRoomAddLikeHelper();
                }
            }
        }
        return mHelper;
    }

    private static long lastClickTime;
    private int tempAddLikeCount = 0;

    public void handleClick(OnAddLikeResultCallBack addLikeResultCallBack) {
        lastClickTime = System.currentTimeMillis();
        sHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                    tempAddLikeCount += 1;
                    if (addLikeResultCallBack != null) {
                        addLikeResultCallBack.onResult(tempAddLikeCount);
                    }
                    tempAddLikeCount = 0;
                } else {
                    tempAddLikeCount += 1;
                }
            }
        }, MIN_CLICK_DELAY_TIME + 10);
    }

    public interface OnAddLikeResultCallBack {
        void onResult(int count);
    }

    public void release() {
        if (sHandler != null) {
            sHandler.removeCallbacksAndMessages(null);
        }
    }
}
