package utils

import (
	"errors"
	"time"
)

var ErrWaitTimeout = errors.New("timed out waiting for the condition")

type ConditionFunc func() (done bool, err error)

// PollImmediate tries a condition func until it returns true, an error, or the timeout
// is reached.
func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error { // it's better to have a naive implementation than importing "k8s.io/apimachinery/pkg/util/wait"
	deadLine := time.Now().Add(timeout)
	for {
		done, err := condition()
		if err != nil {
			return err
		}

		if done {
			return nil
		}

		if time.Now().After(deadLine) {
			return ErrWaitTimeout
		}

		time.Sleep(interval)
	}
}
