package ru.kirillius.pf.sdn.Util;

import java.time.Duration;
import java.time.Instant;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;

public class WorkerUtils {
    @SuppressWarnings("BusyWait")
    public static void waitForCondition(BooleanSupplier condition, long checkInterval) {
        while (!Thread.interrupted() && !condition.getAsBoolean()) {
            try {
                Thread.sleep(checkInterval);
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    public static void waitForCondition(BooleanSupplier condition) {
        waitForCondition(condition, 1000);
    }

    public static void waitForTimer(Supplier<Duration> duration) {
        var start = Instant.now();
        waitForCondition(() -> Duration.between(start, Instant.now()).compareTo(duration.get()) > 0, 1000);
    }

    public abstract static class LoopedWorker implements Runnable {
        protected abstract void doWork();

        @Override
        public final void run() {
            while (!Thread.interrupted()) {
                doWork();
            }
        }
    }
}
