package com.vsu.fcounter.utils;


import java.util.Timer;
import java.util.TimerTask;

public class DebounceTask {
    private Timer timer;
    private Long delay;
    private Runnable runnable;
    private Runnable oncancel;

    public DebounceTask(Runnable runnable, Runnable oncancel, Long delay) {
        this.runnable = runnable;
        this.oncancel = oncancel;
        this.delay = delay;
    }

    public static DebounceTask build(Runnable runnable, Runnable oncancel, Long delay){
        return new DebounceTask(runnable, oncancel, delay);
    }

    public void run(){
        if (timer == null) {
            runnable.run();
        } else timer.cancel();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timer = null;
                if (oncancel != null)
                    oncancel.run();
            }
        }, delay);
    }
}
