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

package handshake

import (
	

	
)

// MessageClientKeyExchange is a DTLS Handshake Message
// With this message, the premaster secret is set, either by direct
// transmission of the RSA-encrypted secret or by the transmission of
// Diffie-Hellman parameters that will allow each side to agree upon
// the same premaster secret.
//
// https://tools.ietf.org/html/rfc5246#section-7.4.7
type MessageClientKeyExchange struct {
	IdentityHint []byte
	PublicKey    []byte

	// for unmarshaling
	KeyExchangeAlgorithm types.KeyExchangeAlgorithm
}

// Type returns the Handshake Type.
func ( MessageClientKeyExchange) () Type {
	return TypeClientKeyExchange
}

// Marshal encodes the Handshake.
func ( *MessageClientKeyExchange) () ( []byte,  error) {
	if .IdentityHint == nil && .PublicKey == nil {
		return nil, errInvalidClientKeyExchange
	}

	if .IdentityHint != nil {
		 = append([]byte{0x00, 0x00}, .IdentityHint...)
		binary.BigEndian.PutUint16(, uint16(len()-2)) //nolint:gosec // G115
	}

	if .PublicKey != nil {
		 = append(, byte(len(.PublicKey)))
		 = append(, .PublicKey...)
	}

	return , nil
}

// Unmarshal populates the message from encoded data.
func ( *MessageClientKeyExchange) ( []byte) error {
	switch {
	case len() < 2:
		return errBufferTooSmall
	case .KeyExchangeAlgorithm == types.KeyExchangeAlgorithmNone:
		return errCipherSuiteUnset
	}

	 := 0
	if .KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmPsk) {
		 := int(binary.BigEndian.Uint16())
		if  > len()-2 {
			return errBufferTooSmall
		}

		.IdentityHint = append([]byte{}, [2:+2]...)
		 +=  + 2
	}

	if .KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmEcdhe) {
		 := int([])
		if  > len()-1- {
			return errBufferTooSmall
		}

		.PublicKey = append([]byte{}, [+1:]...)
	}

	return nil
}