//go:build !tinygo

package helpers

import (
	
	
	

	am 
)

// WaitForAny waits for any of the channels to close, or until the context is
// done, or until the timeout is reached. Returns nil if any channel is
// closed, or ErrTimeout, or ctx.Err().
//
// It's advised to check the state ctx after this call, as it usually means
// expiration and not a timeout.
//
// This function uses reflection to wait for multiple channels at once.
func (
	 context.Context,  time.Duration,  ...<-chan struct{},
) error {
	// TODO test
	// TODO reflection-less selectes for 1/2/3 chans
	// exit early
	if .Err() != nil {
		return .Err()
	}
	if IsDebug() {
		 = 100 * 
	}
	 := time.After()

	// create select cases
	 := make([]reflect.SelectCase, 2+len())
	[0] = reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(.Done()),
	}
	[1] = reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(),
	}
	for ,  := range  {
		[+2] = reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(),
		}
	}

	// wait
	, ,  := reflect.Select()

	switch  {
	case 0:
		// TODO check and log state ctx name
		return .Err()
	case 1:
		return am.ErrTimeout
	default:
		return nil
	}
}

// WaitForErrAny is like WaitForAny, but also waits on WhenErr of a passed
// machine. For state machines with error handling (like retry) it's recommended
// to use [WaitForAny] and measure ticks of [am.StateException] instead.
func (
	 context.Context,  time.Duration,  *am.Machine,
	 ...<-chan struct{},
) error {
	// TODO test
	// TODO reflection-less selectes for 1/2/3 chans
	// exit early
	if .Err() != nil {
		return .Err()
	}
	if IsDebug() {
		 = 100 * 
	}
	 := time.After()

	// create select cases
	 := 3
	 := make([]reflect.SelectCase, +len())
	[0] = reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(.Done()),
	}
	[1] = reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(),
	}
	[2] = reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(),
	}
	for ,  := range  {
		[+] = reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(),
		}
	}

	// wait
	, ,  := reflect.Select()

	switch  {
	case 0:
		// TODO check and log state ctx name (if any)
		return .Err()
	case 1:
		return am.ErrTimeout
	case 2:
		return .Err()
	default:
		return nil
	}
}