package pool

import (
	
	
)

type wantConn struct {
	mu        sync.RWMutex    // protects ctx, done and sending of the result
	ctx       context.Context // context for dial, cleared after delivered or canceled
	cancelCtx context.CancelFunc
	done      bool                // true after delivered or canceled
	result    chan wantConnResult // channel to deliver connection or error
}

// getCtxForDial returns context for dial or nil if connection was delivered or canceled.
func ( *wantConn) () context.Context {
	.mu.RLock()
	defer .mu.RUnlock()

	return .ctx
}

func ( *wantConn) ( *Conn,  error) bool {
	.mu.Lock()
	defer .mu.Unlock()
	if .done {
		return false
	}

	.done = true
	.ctx = nil

	.result <- wantConnResult{cn: , err: }
	close(.result)

	return true
}

func ( *wantConn) () *Conn {
	.mu.Lock()
	var  *Conn
	if .done {
		select {
		case  := <-.result:
			 = .cn
		default:
		}
	} else {
		close(.result)
	}

	.done = true
	.ctx = nil
	.mu.Unlock()

	return 
}

func ( *wantConn) () bool {
	.mu.RLock()
	defer .mu.RUnlock()
	return !.done
}

type wantConnResult struct {
	cn  *Conn
	err error
}

type wantConnQueue struct {
	mu    sync.RWMutex
	items []*wantConn
}

func newWantConnQueue() *wantConnQueue {
	return &wantConnQueue{
		items: make([]*wantConn, 0),
	}
}

func ( *wantConnQueue) ( *wantConn) {
	.mu.Lock()
	defer .mu.Unlock()
	.items = append(.items, )
}

func ( *wantConnQueue) () (*wantConn, bool) {
	.mu.Lock()
	defer .mu.Unlock()

	if len(.items) == 0 {
		return nil, false
	}

	 := .items[0]
	.items = .items[1:]
	return , true
}

func ( *wantConnQueue) () int {
	.mu.Lock()
	defer .mu.Unlock()
	 := 0
	for len(.items) > 0 {
		if .items[0].isOngoing() {
			break
		}

		.items = .items[1:]
		++
	}

	return 
}