package com.common.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by SiKang on 2019/3/1.
 */
@SuppressLint("AppCompatCustomView")
public class CountDownButton extends Button {
    private Timer mTimer;
    private OnCountDownListener onCountDownListener;


    public CountDownButton(Context context) {
        super(context);
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    /**
     * 开始计时
     */
    public void startCountDown(int count, int period, OnCountDownListener listener) {
        stop();
        setEnabled(false);
        this.onCountDownListener = listener;
        mTimer = new Timer();
        mTimer.schedule(new CountDownTask(count), 0, period);
    }

    /**
     * 取消计时
     */
    public void stop() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (onCountDownListener != null) {
            onCountDownListener.onFinish();
            onCountDownListener = null;
        }
        setEnabled(true);
    }


    /**
     * 倒计时
     */
    class CountDownTask extends TimerTask {
        private int count = 0;

        public CountDownTask(int count) {
            this.count = count;
        }

        @Override
        public void run() {
            post(new Runnable() {
                @Override
                public void run() {
                    count--;
                    if (onCountDownListener != null) {
                        onCountDownListener.onCountDown(count);
                    }
                    if (count <= 0) {
                        stop();
                    }
                }
            });
        }
    }


    /**
     * 计时回调
     */
    public interface OnCountDownListener {
        void onCountDown(int index);

        void onFinish();
    }


}
