package httpu

import (
	
	

	
)

// MultiClient dispatches requests out to all the delegated clients.
type MultiClient struct {
	// The HTTPU clients to delegate to.
	delegates []ClientInterface
}

var _ ClientInterface = &MultiClient{}

// NewMultiClient creates a new MultiClient that delegates to all the given
// clients.
func ( []ClientInterface) *MultiClient {
	return &MultiClient{
		delegates: ,
	}
}

// Do implements ClientInterface.Do.
func ( *MultiClient) (
	 *http.Request,
	 time.Duration,
	 int,
) ([]*http.Response, error) {
	 := &errgroup.Group{}

	 := make(chan []*http.Response)
	.Go(func() error {
		defer close()
		return .sendRequests(, , , )
	})

	var  []*http.Response
	.Go(func() error {
		for  := range  {
			 = append(, ...)
		}
		return nil
	})

	return , .Wait()
}

func ( *MultiClient) (
	 chan<- []*http.Response,
	 *http.Request,
	 time.Duration,
	 int,
) error {
	 := &errgroup.Group{}
	for ,  := range .delegates {
		 :=  // copy for closure
		.Go(func() error {
			,  := .Do(, , )
			if  != nil {
				return 
			}
			 <- 
			return nil
		})
	}
	return .Wait()
}

// MultiClientCtx dispatches requests out to all the delegated clients.
type MultiClientCtx struct {
	// The HTTPU clients to delegate to.
	delegates []ClientInterfaceCtx
}

var _ ClientInterfaceCtx = &MultiClientCtx{}

// NewMultiClient creates a new MultiClient that delegates to all the given
// clients.
func ( []ClientInterfaceCtx) *MultiClientCtx {
	return &MultiClientCtx{
		delegates: ,
	}
}

// DoWithContext implements ClientInterfaceCtx.DoWithContext.
func ( *MultiClientCtx) (
	 *http.Request,
	 int,
) ([]*http.Response, error) {
	,  := errgroup.WithContext(.Context())
	 = .WithContext() // so we cancel if the errgroup errors
	 := make(chan []*http.Response)

	// For each client, send the request to it and collect results.
	.Go(func() error {
		defer close()
		return .sendRequestsCtx(, , )
	})

	var  []*http.Response
	.Go(func() error {
		for  := range  {
			 = append(, ...)
		}
		return nil
	})

	return , .Wait()
}

func ( *MultiClientCtx) (
	 chan<- []*http.Response,
	 *http.Request,
	 int,
) error {
	 := &errgroup.Group{}
	for ,  := range .delegates {
		 :=  // copy for closure
		.Go(func() error {
			,  := .DoWithContext(, )
			if  != nil {
				return 
			}
			 <- 
			return nil
		})
	}
	return .Wait()
}