package quic

import (
	
	

	
	
	
)

type receiveFlowController struct {
	//nolint:structcheck // The mutex is used both by the stream and the connection flow controller
	mutex                sync.Mutex
	bytesRead            protocol.ByteCount
	highestReceived      protocol.ByteCount
	receiveWindow        protocol.ByteCount
	receiveWindowSize    protocol.ByteCount
	maxReceiveWindowSize protocol.ByteCount

	allowWindowIncrease func(size protocol.ByteCount) bool

	epochStartTime   monotime.Time
	epochStartOffset protocol.ByteCount
	rttStats         *utils.RTTStats

	logger utils.Logger
}

// needs to be called with locked mutex
func ( *receiveFlowController) ( protocol.ByteCount) {
	.bytesRead += 
}

func ( *receiveFlowController) () bool {
	 := .receiveWindow - .bytesRead
	// update the window when more than the threshold was consumed
	return  <= protocol.ByteCount(float64(.receiveWindowSize)*(1-protocol.WindowUpdateThreshold))
}

// getWindowUpdate updates the receive window, if necessary
// it returns the new offset
func ( *receiveFlowController) ( monotime.Time) protocol.ByteCount {
	if !.hasWindowUpdate() {
		return 0
	}

	.maybeAdjustWindowSize()
	.receiveWindow = .bytesRead + .receiveWindowSize
	return .receiveWindow
}

// maybeAdjustWindowSize increases the receiveWindowSize if we're sending updates too often.
// For details about auto-tuning, see https://docs.google.com/document/d/1SExkMmGiz8VYzV3s9E35JQlJ73vhzCekKkDi85F1qCE/edit?usp=sharing.
func ( *receiveFlowController) ( monotime.Time) {
	 := .bytesRead - .epochStartOffset
	// don't do anything if less than half the window has been consumed
	if  <= .receiveWindowSize/2 {
		return
	}
	 := .rttStats.SmoothedRTT()
	if  == 0 {
		return
	}

	 := float64() / float64(.receiveWindowSize)
	if .Sub(.epochStartTime) < time.Duration(4**float64()) {
		// window is consumed too fast, try to increase the window size
		 := min(2*.receiveWindowSize, .maxReceiveWindowSize)
		if  > .receiveWindowSize && (.allowWindowIncrease == nil || .allowWindowIncrease(-.receiveWindowSize)) {
			.receiveWindowSize = 
		}
	}
	.startNewAutoTuningEpoch()
}

func ( *receiveFlowController) ( monotime.Time) {
	.epochStartTime = 
	.epochStartOffset = .bytesRead
}

func ( *receiveFlowController) () bool {
	return .highestReceived > .receiveWindow
}