package com.yyrh.utils;


/**
 * 手机验证码倒计时
 */
public class TimeDownUtils {

    private static boolean isRunning;
    private static boolean isCancel;
    private static volatile Times times;

    public static void start(int total,TimeCallback timeCallback) {
        if (isRunning) {
            YYLog.d("倒计时还在执行中...");
        } else {
            isRunning = true;
            isCancel = false;
            times = new Times(total,timeCallback);
            times.start();
        }
    }

    public static void cancel() {
        isCancel = true;
        if (isRunning) {
            if (times != null) {
                times.interrupt();
                times = null;
            }
        }
        isRunning = false;
        YYLog.d("TimeDownUtils.cancel");
    }

    public static void resetCallback(TimeCallback timeCallback) {
        if (times != null) {
            times.setCallback(timeCallback);
        }
    }

    public static boolean isRunning() {
        return isRunning;
    }

    public interface TimeCallback {
        void onTime(int time);
    }

    /**
     * 倒计时
     */
    static class Times extends Thread {
        TimeCallback callback;
        int total;

        public Times(int total, TimeCallback callback) {
            this.total = total;
            this.callback = callback;
        }

        public void setCallback(TimeCallback callback) {
            this.callback = callback;
        }

        @Override
        public void run() {
            if (callback != null)
                callback.onTime(total);
            YYLog.d("TimeDownUtils 倒计时开始...");
            for (int i = total; i >= 0; i--) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // ignore
                }
                if (isCancel) {
                    YYLog.d("TimeDownUtils 线程已退出");
                    return;
                }
                if (callback != null)
                    callback.onTime(i);
            }
            cancel();
        }
    }
}
