package com.yyrh.utils;

/**
 * @author #Suyghur.
 * Created on 2021/05/11
 */
public class TimeDownUtils {

    public static boolean isRunning = false;
    private static boolean isCancel = false;


    private volatile static Times times = null;


    public static void start(int time,TimeDownCallback callback) {
        if (isRunning) {
            YYLog.d("TimeDownUtils 倒计时还在执行中...");
        } else {

            isRunning = true;
            isCancel = false;
            times = new Times(time,callback);
            times.start();
        }
    }

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

    public static void resetCallback(TimeDownCallback callback) {
        if (times != null) {
            times.callback = callback;
        }
    }

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

    private static class Times extends Thread {
        private TimeDownCallback callback;
        int time = 0;
        Times(int time,TimeDownCallback callback) {
            this.time = time;
            this.callback = callback;
        }

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