package com.app.baselibrary.utils;

import android.os.CountDownTimer;

/**
 * Date : 2018/6/14.
 * Author:  cxh
 * 倒计时工具
 */

public class CountDownTimerUtils {
    private long mCurrentTime;//当前剩余时间
    private long mDelayTime;//间隔
    private CountDownTimeClick onCountDownTimeClick;

    public void start(long totalTime, long delay, CountDownTimeClick click) {
        onCountDownTimeClick = click;
        mDelayTime = delay;
        mCountDownTimer = new MyCountDownTimer(totalTime, delay);
        mCountDownTimer.start();
    }

    public long pause() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        return mCurrentTime;
    }

    public void resume() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        mCountDownTimer = new MyCountDownTimer(mCurrentTime, mDelayTime);
        mCountDownTimer.start();
    }

    public void stop() {
        mCurrentTime = 0;
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

    private MyCountDownTimer mCountDownTimer;

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (onCountDownTimeClick != null) {
                mCurrentTime = millisUntilFinished;
                onCountDownTimeClick.onTick(millisUntilFinished);
            }
        }

        @Override
        public void onFinish() {
            if (onCountDownTimeClick != null) {
                onCountDownTimeClick.onFinish();
            }
        }
    }

    public interface CountDownTimeClick {
        void onFinish();

        void onTick(long millisUntilFinished);
    }
}
