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

package ice

import (
	
	
)

// CandidateRelay ...
type CandidateRelay struct {
	candidateBase

	relayProtocol string
	onClose       func() error
}

// CandidateRelayConfig is the config required to create a new CandidateRelay.
type CandidateRelayConfig struct {
	CandidateID   string
	Network       string
	Address       string
	Port          int
	Component     uint16
	Priority      uint32
	Foundation    string
	RelAddr       string
	RelPort       int
	RelayProtocol string
	OnClose       func() error
}

// NewCandidateRelay creates a new relay candidate.
func ( *CandidateRelayConfig) (*CandidateRelay, error) {
	 := .CandidateID

	if  == "" {
		 = globalCandidateIDGenerator.Generate()
	}

	,  := netip.ParseAddr(.Address)
	if  != nil {
		return nil, 
	}

	,  := determineNetworkType(.Network, )
	if  != nil {
		return nil, 
	}

	return &CandidateRelay{
		candidateBase: candidateBase{
			id:            ,
			networkType:   ,
			candidateType: CandidateTypeRelay,
			address:       .Address,
			port:          .Port,
			resolvedAddr: &net.UDPAddr{
				IP:   .AsSlice(),
				Port: .Port,
				Zone: .Zone(),
			},
			component:          .Component,
			foundationOverride: .Foundation,
			priorityOverride:   .Priority,
			relatedAddress: &CandidateRelatedAddress{
				Address: .RelAddr,
				Port:    .RelPort,
			},
			remoteCandidateCaches: map[AddrPort]Candidate{},
		},
		relayProtocol: .RelayProtocol,
		onClose:       .OnClose,
	}, nil
}

// LocalPreference returns the local preference for this candidate.
func ( *CandidateRelay) () uint16 {
	// These preference values come from libwebrtc
	// https://github.com/mozilla/libwebrtc/blob/1389c76d9c79839a2ca069df1db48aa3f2e6a1ac/p2p/base/turn_port.cc#L61
	var  uint16
	switch .relayProtocol {
	case relayProtocolTLS, relayProtocolDTLS:
		 = 2
	case tcp:
		 = 1
	default:
		 = 0
	}

	return .candidateBase.LocalPreference() + 
}

// RelayProtocol returns the protocol used between the endpoint and the relay server.
func ( *CandidateRelay) () string {
	return .relayProtocol
}

func ( *CandidateRelay) () error {
	 := .candidateBase.close()
	if .onClose != nil {
		 = .onClose()
		.onClose = nil
	}

	return 
}

func ( *CandidateRelay) () (Candidate, error) {
	,  := .candidateBase.copy()
	if  != nil {
		return nil, 
	}

	if ,  := .(*CandidateRelay);  {
		.relayProtocol = .relayProtocol
	}

	return , nil
}