package cz.moneta.test.dsl.util;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class PollingUtils {
    private static final int POLLING_SECONDS = 5;

    private PollingUtils() {
    }

    public static <TResult> TResult waitForExpectedResultForSeconds(TResult expectedResult, long waitForSeconds,
                                                                    Supplier<TResult> supplier) {
        LocalDateTime start = LocalDateTime.now();

        while (secondsWaitedSince(start) < waitForSeconds) {
            try {
                TimeUnit.SECONDS.sleep(POLLING_SECONDS);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
            TResult result = supplier.get();
            if (Objects.equals(expectedResult, result)) {
                return result;
            }
        }
        return supplier.get();
    }

    private static long secondsWaitedSince(LocalDateTime start) {
        return ChronoUnit.SECONDS.between(start, LocalDateTime.now());
    }
}
