// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package turn

import (
	
	

	
	
	
)

// RelayAddressGeneratorPortRange can be used to only allocate connections inside a defined port range.
// Similar to the RelayAddressGeneratorStatic a static ip address can be set.
type RelayAddressGeneratorPortRange struct {
	// RelayAddress is the IP returned to the user when the relay is created
	RelayAddress net.IP

	// MinPort the minimum port to allocate
	MinPort uint16
	// MaxPort the maximum (inclusive) port to allocate
	MaxPort uint16

	// MaxRetries the amount of tries to allocate a random port in the defined range
	MaxRetries int

	// Rand the random source of numbers
	Rand randutil.MathRandomGenerator

	// Address is passed to Listen/ListenPacket when creating the Relay
	Address string

	Net transport.Net
}

// Validate is called on server startup and confirms the RelayAddressGenerator is properly configured.
func ( *RelayAddressGeneratorPortRange) () error {
	if .Net == nil {
		var  error
		.Net,  = stdnet.NewNet()
		if  != nil {
			return fmt.Errorf("failed to create network: %w", )
		}
	}

	if .Rand == nil {
		.Rand = randutil.NewMathRandomGenerator()
	}

	if .MaxRetries == 0 {
		.MaxRetries = 10
	}

	switch {
	case .MinPort == 0:
		return errMinPortNotZero
	case .MaxPort == 0:
		return errMaxPortNotZero
	case .RelayAddress == nil:
		return errRelayAddressInvalid
	case .Address == "":
		return errListeningAddressInvalid
	default:
		return nil
	}
}

// AllocatePacketConn generates a new PacketConn to receive traffic on and the IP/Port
// to populate the allocation response with.
func ( *RelayAddressGeneratorPortRange) (
	 string,
	 int,
) (net.PacketConn, net.Addr, error) {
	if  != 0 {
		,  := .Net.ListenPacket(, fmt.Sprintf("%s:%d", .Address, ))
		if  != nil {
			return nil, nil, 
		}

		,  := .LocalAddr().(*net.UDPAddr)
		if ! {
			return nil, nil, errNilConn
		}

		.IP = .RelayAddress

		return , , nil
	}

	for  := 0;  < .MaxRetries; ++ {
		 := .MinPort + uint16(.Rand.Intn(int((.MaxPort+1)-.MinPort))) // nolint:gosec // G115 false positive
		,  := .Net.ListenPacket(, fmt.Sprintf("%s:%d", .Address, ))
		if  != nil {
			continue
		}

		,  := .LocalAddr().(*net.UDPAddr)
		if ! {
			return nil, nil, errNilConn
		}

		.IP = .RelayAddress

		return , , nil
	}

	return nil, nil, errMaxRetriesExceeded
}

// AllocateConn generates a new Conn to receive traffic on and the IP/Port
// to populate the allocation response with.
func ( *RelayAddressGeneratorPortRange) (string, int) (net.Conn, net.Addr, error) {
	return nil, nil, errTODO
}