package eu.jonahbauer.wizard.common.machine;

import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class TimeoutContext<S extends TimeoutState<S,C>, C extends TimeoutContext<S,C>> extends Context<S,C> {
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public TimeoutContext(@NotNull S initialState) {
        super(initialState);
    }

    @SuppressWarnings("unchecked")
    public void timeout(@NotNull S currentState, long delay) {
        scheduler.schedule(() -> {
            if (Objects.equals(getState(), currentState)) {
                execute(() -> {
                    if (Objects.equals(getState(), currentState)) {
                        return currentState.onTimeout((C) this);
                    } else {
                        return Optional.empty();
                    }
                });
            }
        }, delay, TimeUnit.MILLISECONDS);
    }

    public void shutdownNow() {
        scheduler.shutdownNow();
    }
}
