/*
 * 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.

// DatagramConnectionTransport2DataType is the corresponding interface of DatagramConnectionTransport2DataType
type DatagramConnectionTransport2DataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetDiscoveryAddress returns DiscoveryAddress (property field)
	GetDiscoveryAddress() ExtensionObject
	// GetDiscoveryAnnounceRate returns DiscoveryAnnounceRate (property field)
	GetDiscoveryAnnounceRate() uint32
	// GetDiscoveryMaxMessageSize returns DiscoveryMaxMessageSize (property field)
	GetDiscoveryMaxMessageSize() uint32
	// GetQosCategory returns QosCategory (property field)
	GetQosCategory() PascalString
	// GetDatagramQos returns DatagramQos (property field)
	GetDatagramQos() []ExtensionObject
	// IsDatagramConnectionTransport2DataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsDatagramConnectionTransport2DataType()
	// CreateBuilder creates a DatagramConnectionTransport2DataTypeBuilder
	CreateDatagramConnectionTransport2DataTypeBuilder() DatagramConnectionTransport2DataTypeBuilder
}

// _DatagramConnectionTransport2DataType is the data-structure of this message
type _DatagramConnectionTransport2DataType struct {
	ExtensionObjectDefinitionContract
	DiscoveryAddress        ExtensionObject
	DiscoveryAnnounceRate   uint32
	DiscoveryMaxMessageSize uint32
	QosCategory             PascalString
	DatagramQos             []ExtensionObject
}

var _ DatagramConnectionTransport2DataType = (*_DatagramConnectionTransport2DataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_DatagramConnectionTransport2DataType)(nil)

// NewDatagramConnectionTransport2DataType factory function for _DatagramConnectionTransport2DataType
func NewDatagramConnectionTransport2DataType(discoveryAddress ExtensionObject, discoveryAnnounceRate uint32, discoveryMaxMessageSize uint32, qosCategory PascalString, datagramQos []ExtensionObject) *_DatagramConnectionTransport2DataType {
	if discoveryAddress == nil {
		panic("discoveryAddress of type ExtensionObject for DatagramConnectionTransport2DataType must not be nil")
	}
	if qosCategory == nil {
		panic("qosCategory of type PascalString for DatagramConnectionTransport2DataType must not be nil")
	}
	_result := &_DatagramConnectionTransport2DataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		DiscoveryAddress:                  discoveryAddress,
		DiscoveryAnnounceRate:             discoveryAnnounceRate,
		DiscoveryMaxMessageSize:           discoveryMaxMessageSize,
		QosCategory:                       qosCategory,
		DatagramQos:                       datagramQos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// DatagramConnectionTransport2DataTypeBuilder is a builder for DatagramConnectionTransport2DataType
type DatagramConnectionTransport2DataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(discoveryAddress ExtensionObject, discoveryAnnounceRate uint32, discoveryMaxMessageSize uint32, qosCategory PascalString, datagramQos []ExtensionObject) DatagramConnectionTransport2DataTypeBuilder
	// WithDiscoveryAddress adds DiscoveryAddress (property field)
	WithDiscoveryAddress(ExtensionObject) DatagramConnectionTransport2DataTypeBuilder
	// WithDiscoveryAddressBuilder adds DiscoveryAddress (property field) which is build by the builder
	WithDiscoveryAddressBuilder(func(ExtensionObjectBuilder) ExtensionObjectBuilder) DatagramConnectionTransport2DataTypeBuilder
	// WithDiscoveryAnnounceRate adds DiscoveryAnnounceRate (property field)
	WithDiscoveryAnnounceRate(uint32) DatagramConnectionTransport2DataTypeBuilder
	// WithDiscoveryMaxMessageSize adds DiscoveryMaxMessageSize (property field)
	WithDiscoveryMaxMessageSize(uint32) DatagramConnectionTransport2DataTypeBuilder
	// WithQosCategory adds QosCategory (property field)
	WithQosCategory(PascalString) DatagramConnectionTransport2DataTypeBuilder
	// WithQosCategoryBuilder adds QosCategory (property field) which is build by the builder
	WithQosCategoryBuilder(func(PascalStringBuilder) PascalStringBuilder) DatagramConnectionTransport2DataTypeBuilder
	// WithDatagramQos adds DatagramQos (property field)
	WithDatagramQos(...ExtensionObject) DatagramConnectionTransport2DataTypeBuilder
	// 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 DatagramConnectionTransport2DataType or returns an error if something is wrong
	Build() (DatagramConnectionTransport2DataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() DatagramConnectionTransport2DataType
}

// NewDatagramConnectionTransport2DataTypeBuilder() creates a DatagramConnectionTransport2DataTypeBuilder
func NewDatagramConnectionTransport2DataTypeBuilder() DatagramConnectionTransport2DataTypeBuilder {
	return &_DatagramConnectionTransport2DataTypeBuilder{_DatagramConnectionTransport2DataType: new(_DatagramConnectionTransport2DataType)}
}

type _DatagramConnectionTransport2DataTypeBuilder struct {
	*_DatagramConnectionTransport2DataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (DatagramConnectionTransport2DataTypeBuilder) = (*_DatagramConnectionTransport2DataTypeBuilder)(nil)

func (b *_DatagramConnectionTransport2DataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._DatagramConnectionTransport2DataType
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithMandatoryFields(discoveryAddress ExtensionObject, discoveryAnnounceRate uint32, discoveryMaxMessageSize uint32, qosCategory PascalString, datagramQos []ExtensionObject) DatagramConnectionTransport2DataTypeBuilder {
	return b.WithDiscoveryAddress(discoveryAddress).WithDiscoveryAnnounceRate(discoveryAnnounceRate).WithDiscoveryMaxMessageSize(discoveryMaxMessageSize).WithQosCategory(qosCategory).WithDatagramQos(datagramQos...)
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithDiscoveryAddress(discoveryAddress ExtensionObject) DatagramConnectionTransport2DataTypeBuilder {
	b.DiscoveryAddress = discoveryAddress
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithDiscoveryAddressBuilder(builderSupplier func(ExtensionObjectBuilder) ExtensionObjectBuilder) DatagramConnectionTransport2DataTypeBuilder {
	builder := builderSupplier(b.DiscoveryAddress.CreateExtensionObjectBuilder())
	var err error
	b.DiscoveryAddress, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ExtensionObjectBuilder failed"))
	}
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithDiscoveryAnnounceRate(discoveryAnnounceRate uint32) DatagramConnectionTransport2DataTypeBuilder {
	b.DiscoveryAnnounceRate = discoveryAnnounceRate
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithDiscoveryMaxMessageSize(discoveryMaxMessageSize uint32) DatagramConnectionTransport2DataTypeBuilder {
	b.DiscoveryMaxMessageSize = discoveryMaxMessageSize
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithQosCategory(qosCategory PascalString) DatagramConnectionTransport2DataTypeBuilder {
	b.QosCategory = qosCategory
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithQosCategoryBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) DatagramConnectionTransport2DataTypeBuilder {
	builder := builderSupplier(b.QosCategory.CreatePascalStringBuilder())
	var err error
	b.QosCategory, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) WithDatagramQos(datagramQos ...ExtensionObject) DatagramConnectionTransport2DataTypeBuilder {
	b.DatagramQos = datagramQos
	return b
}

func (b *_DatagramConnectionTransport2DataTypeBuilder) Build() (DatagramConnectionTransport2DataType, error) {
	if b.DiscoveryAddress == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'discoveryAddress' not set"))
	}
	if b.QosCategory == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'qosCategory' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._DatagramConnectionTransport2DataType.deepCopy(), nil
}

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

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

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

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

// CreateDatagramConnectionTransport2DataTypeBuilder creates a DatagramConnectionTransport2DataTypeBuilder
func (b *_DatagramConnectionTransport2DataType) CreateDatagramConnectionTransport2DataTypeBuilder() DatagramConnectionTransport2DataTypeBuilder {
	if b == nil {
		return NewDatagramConnectionTransport2DataTypeBuilder()
	}
	return &_DatagramConnectionTransport2DataTypeBuilder{_DatagramConnectionTransport2DataType: b.deepCopy()}
}

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

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

func (m *_DatagramConnectionTransport2DataType) GetExtensionId() int32 {
	return int32(23614)
}

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

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

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

func (m *_DatagramConnectionTransport2DataType) GetDiscoveryAddress() ExtensionObject {
	return m.DiscoveryAddress
}

func (m *_DatagramConnectionTransport2DataType) GetDiscoveryAnnounceRate() uint32 {
	return m.DiscoveryAnnounceRate
}

func (m *_DatagramConnectionTransport2DataType) GetDiscoveryMaxMessageSize() uint32 {
	return m.DiscoveryMaxMessageSize
}

func (m *_DatagramConnectionTransport2DataType) GetQosCategory() PascalString {
	return m.QosCategory
}

func (m *_DatagramConnectionTransport2DataType) GetDatagramQos() []ExtensionObject {
	return m.DatagramQos
}

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

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

func (m *_DatagramConnectionTransport2DataType) GetTypeName() string {
	return "DatagramConnectionTransport2DataType"
}

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

	// Simple field (discoveryAddress)
	lengthInBits += m.DiscoveryAddress.GetLengthInBits(ctx)

	// Simple field (discoveryAnnounceRate)
	lengthInBits += 32

	// Simple field (discoveryMaxMessageSize)
	lengthInBits += 32

	// Simple field (qosCategory)
	lengthInBits += m.QosCategory.GetLengthInBits(ctx)

	// Implicit Field (noOfDatagramQos)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

	discoveryAddress, err := ReadSimpleField[ExtensionObject](ctx, "discoveryAddress", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'discoveryAddress' field"))
	}
	m.DiscoveryAddress = discoveryAddress

	discoveryAnnounceRate, err := ReadSimpleField(ctx, "discoveryAnnounceRate", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'discoveryAnnounceRate' field"))
	}
	m.DiscoveryAnnounceRate = discoveryAnnounceRate

	discoveryMaxMessageSize, err := ReadSimpleField(ctx, "discoveryMaxMessageSize", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'discoveryMaxMessageSize' field"))
	}
	m.DiscoveryMaxMessageSize = discoveryMaxMessageSize

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

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

	datagramQos, err := ReadCountArrayField[ExtensionObject](ctx, "datagramQos", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer), uint64(noOfDatagramQos))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'datagramQos' field"))
	}
	m.DatagramQos = datagramQos

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

	return m, nil
}

func (m *_DatagramConnectionTransport2DataType) 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 *_DatagramConnectionTransport2DataType) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("DatagramConnectionTransport2DataType"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for DatagramConnectionTransport2DataType")
		}

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

		if err := WriteSimpleField[uint32](ctx, "discoveryAnnounceRate", m.GetDiscoveryAnnounceRate(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'discoveryAnnounceRate' field")
		}

		if err := WriteSimpleField[uint32](ctx, "discoveryMaxMessageSize", m.GetDiscoveryMaxMessageSize(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'discoveryMaxMessageSize' field")
		}

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

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

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

func (m *_DatagramConnectionTransport2DataType) IsDatagramConnectionTransport2DataType() {}

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

func (m *_DatagramConnectionTransport2DataType) deepCopy() *_DatagramConnectionTransport2DataType {
	if m == nil {
		return nil
	}
	_DatagramConnectionTransport2DataTypeCopy := &_DatagramConnectionTransport2DataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ExtensionObject](m.DiscoveryAddress),
		m.DiscoveryAnnounceRate,
		m.DiscoveryMaxMessageSize,
		utils.DeepCopy[PascalString](m.QosCategory),
		utils.DeepCopySlice[ExtensionObject, ExtensionObject](m.DatagramQos),
	}
	_DatagramConnectionTransport2DataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _DatagramConnectionTransport2DataTypeCopy
}

func (m *_DatagramConnectionTransport2DataType) 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()
}
