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


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

public class TimerUtil {
    // 周期时间
    private final long period;

    private OnTickListener listener;

    private Timer timer = new Timer();

    private TimerTask task;

    private AtomicInteger count = new AtomicInteger(0);

    public interface OnTickListener {
        void onStart();

        void onTick(int count, long period);
    }

    public static class Builder {
        // 周期时间
        private long period = 16;

        private OnTickListener listener = null;

        public Builder() {
        }


        public Builder setPeriod(long period) {
            assert period > 0;
            this.period = period;
            return this;
        }

        public Builder setOnTick(OnTickListener listener) {
            this.listener = listener;
            return this;
        }

        public TimerUtil build() {
            return new TimerUtil(period, listener);
        }
    }

    private TimerUtil(long period, OnTickListener listener) {
        this.period = period;
        this.listener = listener;
    }

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

    public void start() {
        if (task != null) {
            task.cancel();
            timer.purge();
        }

        if (listener != null) {
            listener.onStart();
        }

        task = new TimerTask() {
            @Override
            public void run() {
                count.addAndGet(1);
                if (listener != null) {
                    listener.onTick(count.get(), period);
                }
            }
        };

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

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

    public void resume() {
        task = new TimerTask() {
            @Override
            public void run() {
                count.addAndGet(1);
                if (listener != null) {
                    listener.onTick(count.get(), period);
                }
            }
        };

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

    public void cancel() {
        timer.cancel();
    }

    public void reset() {
        if (task != null) {
            task.cancel();
        }
        timer.purge();
        count.set(0);
        listener.onTick(0, period);
    }
}
