package com.tencent.liteav.demo.superplayer.util;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class CountDownUtil {
    // 倒计时的监听者
    public interface OnTickListener {
        void onTimeout(CountDownUtil util);
    }

    private static final CountDownUtil INSTANCE = new CountDownUtil();

    public static CountDownUtil getInstance() {
        return INSTANCE;
    }

    public static void addListener(OnTickListener listener) {
        INSTANCE.listeners.add(listener);
    }

    public static void removeListener(OnTickListener listener) {
        INSTANCE.listeners.remove(listener);
    }

    // 周期时间
    private static final long period = 1000;

    // 定时数
    private long maxCount = Integer.MAX_VALUE;

    // 回调监听对象
    private final ArrayList<CountDownUtil.OnTickListener> listeners = new ArrayList<>();

    // 计时器
    private Timer timer;

    // 计数器
    private final AtomicLong count = new AtomicLong(0L);

    private CountDownUtil() {
    }


    public void startOrResume() {
        pause();
        setupTask();
    }

    private void setupTask() {
        timer = new Timer();
        // 计时任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                count.addAndGet(1);

                if (count.get() >= maxCount) {
                    pause();

                    for (OnTickListener listener : listeners) {
                        listener.onTimeout(CountDownUtil.this);
                    }
                }
            }
        };

        timer.schedule(task, 0, period);
    }

    public void pause() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void reset(long maxCount, Boolean autoStart) {
        this.maxCount = maxCount;
        pause();
        count.set(0);
        if (autoStart) startOrResume();
    }

    public Long getCount() {
        return count.get();
    }
}
