/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package model

import (
	"context"
	stdErrors "errors"
	"fmt"

	"github.com/pkg/errors"
	"github.com/rs/zerolog"

	. "github.com/apache/plc4x/plc4go/spi/codegen/fields"
	. "github.com/apache/plc4x/plc4go/spi/codegen/io"
	"github.com/apache/plc4x/plc4go/spi/utils"
)

// Code generated by code-generation. DO NOT EDIT.

// DtlsPubSubConnectionDataType is the corresponding interface of DtlsPubSubConnectionDataType
type DtlsPubSubConnectionDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetClientCipherSuite returns ClientCipherSuite (property field)
	GetClientCipherSuite() PascalString
	// GetServerCipherSuites returns ServerCipherSuites (property field)
	GetServerCipherSuites() []PascalString
	// GetZeroRTT returns ZeroRTT (property field)
	GetZeroRTT() bool
	// GetCertificateGroupId returns CertificateGroupId (property field)
	GetCertificateGroupId() NodeId
	// GetVerifyClientCertificate returns VerifyClientCertificate (property field)
	GetVerifyClientCertificate() bool
	// IsDtlsPubSubConnectionDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsDtlsPubSubConnectionDataType()
	// CreateBuilder creates a DtlsPubSubConnectionDataTypeBuilder
	CreateDtlsPubSubConnectionDataTypeBuilder() DtlsPubSubConnectionDataTypeBuilder
}

// _DtlsPubSubConnectionDataType is the data-structure of this message
type _DtlsPubSubConnectionDataType struct {
	ExtensionObjectDefinitionContract
	ClientCipherSuite       PascalString
	ServerCipherSuites      []PascalString
	ZeroRTT                 bool
	CertificateGroupId      NodeId
	VerifyClientCertificate bool
	// Reserved Fields
	reservedField0 *uint8
	reservedField1 *uint8
}

var _ DtlsPubSubConnectionDataType = (*_DtlsPubSubConnectionDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_DtlsPubSubConnectionDataType)(nil)

// NewDtlsPubSubConnectionDataType factory function for _DtlsPubSubConnectionDataType
func NewDtlsPubSubConnectionDataType(clientCipherSuite PascalString, serverCipherSuites []PascalString, zeroRTT bool, certificateGroupId NodeId, verifyClientCertificate bool) *_DtlsPubSubConnectionDataType {
	if clientCipherSuite == nil {
		panic("clientCipherSuite of type PascalString for DtlsPubSubConnectionDataType must not be nil")
	}
	if certificateGroupId == nil {
		panic("certificateGroupId of type NodeId for DtlsPubSubConnectionDataType must not be nil")
	}
	_result := &_DtlsPubSubConnectionDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ClientCipherSuite:                 clientCipherSuite,
		ServerCipherSuites:                serverCipherSuites,
		ZeroRTT:                           zeroRTT,
		CertificateGroupId:                certificateGroupId,
		VerifyClientCertificate:           verifyClientCertificate,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Builder
///////////////////////

// DtlsPubSubConnectionDataTypeBuilder is a builder for DtlsPubSubConnectionDataType
type DtlsPubSubConnectionDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(clientCipherSuite PascalString, serverCipherSuites []PascalString, zeroRTT bool, certificateGroupId NodeId, verifyClientCertificate bool) DtlsPubSubConnectionDataTypeBuilder
	// WithClientCipherSuite adds ClientCipherSuite (property field)
	WithClientCipherSuite(PascalString) DtlsPubSubConnectionDataTypeBuilder
	// WithClientCipherSuiteBuilder adds ClientCipherSuite (property field) which is build by the builder
	WithClientCipherSuiteBuilder(func(PascalStringBuilder) PascalStringBuilder) DtlsPubSubConnectionDataTypeBuilder
	// WithServerCipherSuites adds ServerCipherSuites (property field)
	WithServerCipherSuites(...PascalString) DtlsPubSubConnectionDataTypeBuilder
	// WithZeroRTT adds ZeroRTT (property field)
	WithZeroRTT(bool) DtlsPubSubConnectionDataTypeBuilder
	// WithCertificateGroupId adds CertificateGroupId (property field)
	WithCertificateGroupId(NodeId) DtlsPubSubConnectionDataTypeBuilder
	// WithCertificateGroupIdBuilder adds CertificateGroupId (property field) which is build by the builder
	WithCertificateGroupIdBuilder(func(NodeIdBuilder) NodeIdBuilder) DtlsPubSubConnectionDataTypeBuilder
	// WithVerifyClientCertificate adds VerifyClientCertificate (property field)
	WithVerifyClientCertificate(bool) DtlsPubSubConnectionDataTypeBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ExtensionObjectDefinitionBuilder
	// Build builds the DtlsPubSubConnectionDataType or returns an error if something is wrong
	Build() (DtlsPubSubConnectionDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() DtlsPubSubConnectionDataType
}

// NewDtlsPubSubConnectionDataTypeBuilder() creates a DtlsPubSubConnectionDataTypeBuilder
func NewDtlsPubSubConnectionDataTypeBuilder() DtlsPubSubConnectionDataTypeBuilder {
	return &_DtlsPubSubConnectionDataTypeBuilder{_DtlsPubSubConnectionDataType: new(_DtlsPubSubConnectionDataType)}
}

type _DtlsPubSubConnectionDataTypeBuilder struct {
	*_DtlsPubSubConnectionDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (DtlsPubSubConnectionDataTypeBuilder) = (*_DtlsPubSubConnectionDataTypeBuilder)(nil)

func (b *_DtlsPubSubConnectionDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._DtlsPubSubConnectionDataType
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithMandatoryFields(clientCipherSuite PascalString, serverCipherSuites []PascalString, zeroRTT bool, certificateGroupId NodeId, verifyClientCertificate bool) DtlsPubSubConnectionDataTypeBuilder {
	return b.WithClientCipherSuite(clientCipherSuite).WithServerCipherSuites(serverCipherSuites...).WithZeroRTT(zeroRTT).WithCertificateGroupId(certificateGroupId).WithVerifyClientCertificate(verifyClientCertificate)
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithClientCipherSuite(clientCipherSuite PascalString) DtlsPubSubConnectionDataTypeBuilder {
	b.ClientCipherSuite = clientCipherSuite
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithClientCipherSuiteBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) DtlsPubSubConnectionDataTypeBuilder {
	builder := builderSupplier(b.ClientCipherSuite.CreatePascalStringBuilder())
	var err error
	b.ClientCipherSuite, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithServerCipherSuites(serverCipherSuites ...PascalString) DtlsPubSubConnectionDataTypeBuilder {
	b.ServerCipherSuites = serverCipherSuites
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithZeroRTT(zeroRTT bool) DtlsPubSubConnectionDataTypeBuilder {
	b.ZeroRTT = zeroRTT
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithCertificateGroupId(certificateGroupId NodeId) DtlsPubSubConnectionDataTypeBuilder {
	b.CertificateGroupId = certificateGroupId
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithCertificateGroupIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) DtlsPubSubConnectionDataTypeBuilder {
	builder := builderSupplier(b.CertificateGroupId.CreateNodeIdBuilder())
	var err error
	b.CertificateGroupId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) WithVerifyClientCertificate(verifyClientCertificate bool) DtlsPubSubConnectionDataTypeBuilder {
	b.VerifyClientCertificate = verifyClientCertificate
	return b
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) Build() (DtlsPubSubConnectionDataType, error) {
	if b.ClientCipherSuite == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'clientCipherSuite' not set"))
	}
	if b.CertificateGroupId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'certificateGroupId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._DtlsPubSubConnectionDataType.deepCopy(), nil
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) MustBuild() DtlsPubSubConnectionDataType {
	build, err := b.Build()
	if err != nil {
		panic(err)
	}
	return build
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) Done() ExtensionObjectDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewExtensionObjectDefinitionBuilder().(*_ExtensionObjectDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) buildForExtensionObjectDefinition() (ExtensionObjectDefinition, error) {
	return b.Build()
}

func (b *_DtlsPubSubConnectionDataTypeBuilder) DeepCopy() any {
	_copy := b.CreateDtlsPubSubConnectionDataTypeBuilder().(*_DtlsPubSubConnectionDataTypeBuilder)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateDtlsPubSubConnectionDataTypeBuilder creates a DtlsPubSubConnectionDataTypeBuilder
func (b *_DtlsPubSubConnectionDataType) CreateDtlsPubSubConnectionDataTypeBuilder() DtlsPubSubConnectionDataTypeBuilder {
	if b == nil {
		return NewDtlsPubSubConnectionDataTypeBuilder()
	}
	return &_DtlsPubSubConnectionDataTypeBuilder{_DtlsPubSubConnectionDataType: b.deepCopy()}
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for discriminator values.
///////////////////////

func (m *_DtlsPubSubConnectionDataType) GetExtensionId() int32 {
	return int32(18796)
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

func (m *_DtlsPubSubConnectionDataType) GetParent() ExtensionObjectDefinitionContract {
	return m.ExtensionObjectDefinitionContract
}

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for property fields.
///////////////////////

func (m *_DtlsPubSubConnectionDataType) GetClientCipherSuite() PascalString {
	return m.ClientCipherSuite
}

func (m *_DtlsPubSubConnectionDataType) GetServerCipherSuites() []PascalString {
	return m.ServerCipherSuites
}

func (m *_DtlsPubSubConnectionDataType) GetZeroRTT() bool {
	return m.ZeroRTT
}

func (m *_DtlsPubSubConnectionDataType) GetCertificateGroupId() NodeId {
	return m.CertificateGroupId
}

func (m *_DtlsPubSubConnectionDataType) GetVerifyClientCertificate() bool {
	return m.VerifyClientCertificate
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

// Deprecated: use the interface for direct cast
func CastDtlsPubSubConnectionDataType(structType any) DtlsPubSubConnectionDataType {
	if casted, ok := structType.(DtlsPubSubConnectionDataType); ok {
		return casted
	}
	if casted, ok := structType.(*DtlsPubSubConnectionDataType); ok {
		return *casted
	}
	return nil
}

func (m *_DtlsPubSubConnectionDataType) GetTypeName() string {
	return "DtlsPubSubConnectionDataType"
}

func (m *_DtlsPubSubConnectionDataType) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).getLengthInBits(ctx))

	// Simple field (clientCipherSuite)
	lengthInBits += m.ClientCipherSuite.GetLengthInBits(ctx)

	// Implicit Field (noOfServerCipherSuites)
	lengthInBits += 32

	// Array field
	if len(m.ServerCipherSuites) > 0 {
		for _curItem, element := range m.ServerCipherSuites {
			arrayCtx := utils.CreateArrayContext(ctx, len(m.ServerCipherSuites), _curItem)
			lengthInBits += element.GetLengthInBits(arrayCtx)
		}
	}

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (zeroRTT)
	lengthInBits += 1

	// Simple field (certificateGroupId)
	lengthInBits += m.CertificateGroupId.GetLengthInBits(ctx)

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (verifyClientCertificate)
	lengthInBits += 1

	return lengthInBits
}

func (m *_DtlsPubSubConnectionDataType) GetLengthInBytes(ctx context.Context) uint16 {
	return m.GetLengthInBits(ctx) / 8
}

func (m *_DtlsPubSubConnectionDataType) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__dtlsPubSubConnectionDataType DtlsPubSubConnectionDataType, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("DtlsPubSubConnectionDataType"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for DtlsPubSubConnectionDataType")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	clientCipherSuite, err := ReadSimpleField[PascalString](ctx, "clientCipherSuite", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'clientCipherSuite' field"))
	}
	m.ClientCipherSuite = clientCipherSuite

	noOfServerCipherSuites, err := ReadImplicitField[int32](ctx, "noOfServerCipherSuites", ReadSignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'noOfServerCipherSuites' field"))
	}
	_ = noOfServerCipherSuites

	serverCipherSuites, err := ReadCountArrayField[PascalString](ctx, "serverCipherSuites", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer), uint64(noOfServerCipherSuites))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serverCipherSuites' field"))
	}
	m.ServerCipherSuites = serverCipherSuites

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(7)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField0 = reservedField0

	zeroRTT, err := ReadSimpleField(ctx, "zeroRTT", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'zeroRTT' field"))
	}
	m.ZeroRTT = zeroRTT

	certificateGroupId, err := ReadSimpleField[NodeId](ctx, "certificateGroupId", ReadComplex[NodeId](NodeIdParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'certificateGroupId' field"))
	}
	m.CertificateGroupId = certificateGroupId

	reservedField1, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(7)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField1 = reservedField1

	verifyClientCertificate, err := ReadSimpleField(ctx, "verifyClientCertificate", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'verifyClientCertificate' field"))
	}
	m.VerifyClientCertificate = verifyClientCertificate

	if closeErr := readBuffer.CloseContext("DtlsPubSubConnectionDataType"); closeErr != nil {
		return nil, errors.Wrap(closeErr, "Error closing for DtlsPubSubConnectionDataType")
	}

	return m, nil
}

func (m *_DtlsPubSubConnectionDataType) Serialize() ([]byte, error) {
	wb := utils.NewWriteBufferByteBased(utils.WithInitialSizeForByteBasedBuffer(int(m.GetLengthInBytes(context.Background()))))
	if err := m.SerializeWithWriteBuffer(context.Background(), wb); err != nil {
		return nil, err
	}
	return wb.GetBytes(), nil
}

func (m *_DtlsPubSubConnectionDataType) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("DtlsPubSubConnectionDataType"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for DtlsPubSubConnectionDataType")
		}

		if err := WriteSimpleField[PascalString](ctx, "clientCipherSuite", m.GetClientCipherSuite(), WriteComplex[PascalString](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'clientCipherSuite' field")
		}
		noOfServerCipherSuites := int32(utils.InlineIf(bool((m.GetServerCipherSuites()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetServerCipherSuites()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfServerCipherSuites", noOfServerCipherSuites, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfServerCipherSuites' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "serverCipherSuites", m.GetServerCipherSuites(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'serverCipherSuites' field")
		}

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 7)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 1")
		}

		if err := WriteSimpleField[bool](ctx, "zeroRTT", m.GetZeroRTT(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'zeroRTT' field")
		}

		if err := WriteSimpleField[NodeId](ctx, "certificateGroupId", m.GetCertificateGroupId(), WriteComplex[NodeId](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'certificateGroupId' field")
		}

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 7)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 2")
		}

		if err := WriteSimpleField[bool](ctx, "verifyClientCertificate", m.GetVerifyClientCertificate(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'verifyClientCertificate' field")
		}

		if popErr := writeBuffer.PopContext("DtlsPubSubConnectionDataType"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for DtlsPubSubConnectionDataType")
		}
		return nil
	}
	return m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_DtlsPubSubConnectionDataType) IsDtlsPubSubConnectionDataType() {}

func (m *_DtlsPubSubConnectionDataType) DeepCopy() any {
	return m.deepCopy()
}

func (m *_DtlsPubSubConnectionDataType) deepCopy() *_DtlsPubSubConnectionDataType {
	if m == nil {
		return nil
	}
	_DtlsPubSubConnectionDataTypeCopy := &_DtlsPubSubConnectionDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.ClientCipherSuite),
		utils.DeepCopySlice[PascalString, PascalString](m.ServerCipherSuites),
		m.ZeroRTT,
		utils.DeepCopy[NodeId](m.CertificateGroupId),
		m.VerifyClientCertificate,
		m.reservedField0,
		m.reservedField1,
	}
	_DtlsPubSubConnectionDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _DtlsPubSubConnectionDataTypeCopy
}

func (m *_DtlsPubSubConnectionDataType) String() string {
	if m == nil {
		return "<nil>"
	}
	wb := utils.NewWriteBufferBoxBased(
		utils.WithWriteBufferBoxBasedMergeSingleBoxes(),
		utils.WithWriteBufferBoxBasedOmitEmptyBoxes(),
		utils.WithWriteBufferBoxBasedPrintPosLengthFooter(),
	)
	if err := wb.WriteSerializable(context.Background(), m); err != nil {
		return err.Error()
	}
	return wb.GetBox().String()
}
