package quic

import (
	
	
	

	
	
	
)

type incomingStream interface {
	closeForShutdown(error)
}

// When a stream is deleted before it was accepted, we can't delete it from the map immediately.
// We need to wait until the application accepts it, and delete it then.
type incomingStreamEntry[ incomingStream] struct {
	stream       
	shouldDelete bool
}

type incomingStreamsMap[ incomingStream] struct {
	mutex         sync.RWMutex
	newStreamChan chan struct{}

	streamType protocol.StreamType
	streams    map[protocol.StreamID]incomingStreamEntry[]

	nextStreamToAccept protocol.StreamID // the next stream that will be returned by AcceptStream()
	nextStreamToOpen   protocol.StreamID // the highest stream that the peer opened
	maxStream          protocol.StreamID // the highest stream that the peer is allowed to open
	maxNumStreams      uint64            // maximum number of streams

	newStream        func(protocol.StreamID) 
	queueMaxStreamID func(*wire.MaxStreamsFrame)

	closeErr error
}

func newIncomingStreamsMap[ incomingStream](
	 protocol.StreamType,
	 func(protocol.StreamID) ,
	 uint64,
	 func(wire.Frame),
	 protocol.Perspective,
) *incomingStreamsMap[] {
	var  protocol.StreamID
	switch {
	case  == protocol.StreamTypeBidi &&  == protocol.PerspectiveServer:
		 = protocol.FirstIncomingBidiStreamServer
	case  == protocol.StreamTypeBidi &&  == protocol.PerspectiveClient:
		 = protocol.FirstIncomingBidiStreamClient
	case  == protocol.StreamTypeUni &&  == protocol.PerspectiveServer:
		 = protocol.FirstIncomingUniStreamServer
	case  == protocol.StreamTypeUni &&  == protocol.PerspectiveClient:
		 = protocol.FirstIncomingUniStreamClient
	}
	return &incomingStreamsMap[]{
		newStreamChan:      make(chan struct{}, 1),
		streamType:         ,
		streams:            make(map[protocol.StreamID]incomingStreamEntry[]),
		maxStream:          protocol.StreamNum().StreamID(, .Opposite()),
		maxNumStreams:      ,
		newStream:          ,
		nextStreamToOpen:   ,
		nextStreamToAccept: ,
		queueMaxStreamID:   func( *wire.MaxStreamsFrame) { () },
	}
}

func ( *incomingStreamsMap[]) ( context.Context) (, error) {
	// drain the newStreamChan, so we don't check the map twice if the stream doesn't exist
	select {
	case <-.newStreamChan:
	default:
	}

	.mutex.Lock()

	var  protocol.StreamID
	var  incomingStreamEntry[]
	for {
		 = .nextStreamToAccept
		if .closeErr != nil {
			.mutex.Unlock()
			return *new(), .closeErr
		}
		var  bool
		,  = .streams[]
		if  {
			break
		}
		.mutex.Unlock()
		select {
		case <-.Done():
			return *new(), .Err()
		case <-.newStreamChan:
		}
		.mutex.Lock()
	}
	.nextStreamToAccept += 4
	// If this stream was completed before being accepted, we can delete it now.
	if .shouldDelete {
		if  := .deleteStream();  != nil {
			.mutex.Unlock()
			return *new(), 
		}
	}
	.mutex.Unlock()
	return .stream, nil
}

func ( *incomingStreamsMap[]) ( protocol.StreamID) (, error) {
	.mutex.RLock()
	if  > .maxStream {
		.mutex.RUnlock()
		return *new(), &qerr.TransportError{
			ErrorCode:    qerr.StreamLimitError,
			ErrorMessage: fmt.Sprintf("peer tried to open stream %d (current limit: %d)", , .maxStream),
		}
	}
	// if the num is smaller than the highest we accepted
	// * this stream exists in the map, and we can return it, or
	// * this stream was already closed, then we can return the nil
	if  < .nextStreamToOpen {
		var  
		// If the stream was already queued for deletion, and is just waiting to be accepted, don't return it.
		if ,  := .streams[];  && !.shouldDelete {
			 = .stream
		}
		.mutex.RUnlock()
		return , nil
	}
	.mutex.RUnlock()

	.mutex.Lock()
	// no need to check the two error conditions from above again
	// * maxStream can only increase, so if the id was valid before, it definitely is valid now
	// * highestStream is only modified by this function
	for  := .nextStreamToOpen;  <= ;  += 4 {
		.streams[] = incomingStreamEntry[]{stream: .newStream()}
		select {
		case .newStreamChan <- struct{}{}:
		default:
		}
	}
	.nextStreamToOpen =  + 4
	 := .streams[]
	.mutex.Unlock()
	return .stream, nil
}

func ( *incomingStreamsMap[]) ( protocol.StreamID) error {
	.mutex.Lock()
	defer .mutex.Unlock()

	if  := .deleteStream();  != nil {
		return &qerr.TransportError{
			ErrorCode:    qerr.StreamStateError,
			ErrorMessage: .Error(),
		}
	}
	return nil
}

func ( *incomingStreamsMap[]) ( protocol.StreamID) error {
	if ,  := .streams[]; ! {
		return fmt.Errorf("tried to delete unknown incoming stream %d", )
	}

	// Don't delete this stream yet, if it was not yet accepted.
	// Just save it to streamsToDelete map, to make sure it is deleted as soon as it gets accepted.
	if  >= .nextStreamToAccept {
		,  := .streams[]
		if  && .shouldDelete {
			return fmt.Errorf("tried to delete incoming stream %d multiple times", )
		}
		.shouldDelete = true
		.streams[] =  // can't assign to struct in map, so we need to reassign
		return nil
	}

	delete(.streams, )
	// queue a MAX_STREAM_ID frame, giving the peer the option to open a new stream
	if .maxNumStreams > uint64(len(.streams)) {
		 := .nextStreamToOpen + 4*protocol.StreamID(.maxNumStreams-uint64(len(.streams))-1)
		// never send a value larger than the maximum value for a stream number
		if  <= protocol.MaxStreamID {
			.maxStream = 
			.queueMaxStreamID(&wire.MaxStreamsFrame{
				Type:         .streamType,
				MaxStreamNum: .maxStream.StreamNum(),
			})
		}
	}
	return nil
}

func ( *incomingStreamsMap[]) ( error) {
	.mutex.Lock()
	.closeErr = 
	for ,  := range .streams {
		.stream.closeForShutdown()
	}
	.mutex.Unlock()
	close(.newStreamChan)
}