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

// ApplicationIdentityDataType is the corresponding interface of ApplicationIdentityDataType
type ApplicationIdentityDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetName returns Name (property field)
	GetName() PascalString
	// GetRecordProperties returns RecordProperties (property field)
	GetRecordProperties() []KeyValuePair
	// GetApplicationUri returns ApplicationUri (property field)
	GetApplicationUri() PascalString
	// GetApplicationNames returns ApplicationNames (property field)
	GetApplicationNames() []LocalizedText
	// GetAdditionalServers returns AdditionalServers (property field)
	GetAdditionalServers() []ApplicationDescription
	// IsApplicationIdentityDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsApplicationIdentityDataType()
	// CreateBuilder creates a ApplicationIdentityDataTypeBuilder
	CreateApplicationIdentityDataTypeBuilder() ApplicationIdentityDataTypeBuilder
}

// _ApplicationIdentityDataType is the data-structure of this message
type _ApplicationIdentityDataType struct {
	ExtensionObjectDefinitionContract
	Name              PascalString
	RecordProperties  []KeyValuePair
	ApplicationUri    PascalString
	ApplicationNames  []LocalizedText
	AdditionalServers []ApplicationDescription
}

var _ ApplicationIdentityDataType = (*_ApplicationIdentityDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ApplicationIdentityDataType)(nil)

// NewApplicationIdentityDataType factory function for _ApplicationIdentityDataType
func NewApplicationIdentityDataType(name PascalString, recordProperties []KeyValuePair, applicationUri PascalString, applicationNames []LocalizedText, additionalServers []ApplicationDescription) *_ApplicationIdentityDataType {
	if name == nil {
		panic("name of type PascalString for ApplicationIdentityDataType must not be nil")
	}
	if applicationUri == nil {
		panic("applicationUri of type PascalString for ApplicationIdentityDataType must not be nil")
	}
	_result := &_ApplicationIdentityDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Name:                              name,
		RecordProperties:                  recordProperties,
		ApplicationUri:                    applicationUri,
		ApplicationNames:                  applicationNames,
		AdditionalServers:                 additionalServers,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ApplicationIdentityDataTypeBuilder is a builder for ApplicationIdentityDataType
type ApplicationIdentityDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, applicationUri PascalString, applicationNames []LocalizedText, additionalServers []ApplicationDescription) ApplicationIdentityDataTypeBuilder
	// WithName adds Name (property field)
	WithName(PascalString) ApplicationIdentityDataTypeBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) ApplicationIdentityDataTypeBuilder
	// WithRecordProperties adds RecordProperties (property field)
	WithRecordProperties(...KeyValuePair) ApplicationIdentityDataTypeBuilder
	// WithApplicationUri adds ApplicationUri (property field)
	WithApplicationUri(PascalString) ApplicationIdentityDataTypeBuilder
	// WithApplicationUriBuilder adds ApplicationUri (property field) which is build by the builder
	WithApplicationUriBuilder(func(PascalStringBuilder) PascalStringBuilder) ApplicationIdentityDataTypeBuilder
	// WithApplicationNames adds ApplicationNames (property field)
	WithApplicationNames(...LocalizedText) ApplicationIdentityDataTypeBuilder
	// WithAdditionalServers adds AdditionalServers (property field)
	WithAdditionalServers(...ApplicationDescription) ApplicationIdentityDataTypeBuilder
	// 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 ApplicationIdentityDataType or returns an error if something is wrong
	Build() (ApplicationIdentityDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ApplicationIdentityDataType
}

// NewApplicationIdentityDataTypeBuilder() creates a ApplicationIdentityDataTypeBuilder
func NewApplicationIdentityDataTypeBuilder() ApplicationIdentityDataTypeBuilder {
	return &_ApplicationIdentityDataTypeBuilder{_ApplicationIdentityDataType: new(_ApplicationIdentityDataType)}
}

type _ApplicationIdentityDataTypeBuilder struct {
	*_ApplicationIdentityDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ApplicationIdentityDataTypeBuilder) = (*_ApplicationIdentityDataTypeBuilder)(nil)

func (b *_ApplicationIdentityDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ApplicationIdentityDataType
}

func (b *_ApplicationIdentityDataTypeBuilder) WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, applicationUri PascalString, applicationNames []LocalizedText, additionalServers []ApplicationDescription) ApplicationIdentityDataTypeBuilder {
	return b.WithName(name).WithRecordProperties(recordProperties...).WithApplicationUri(applicationUri).WithApplicationNames(applicationNames...).WithAdditionalServers(additionalServers...)
}

func (b *_ApplicationIdentityDataTypeBuilder) WithName(name PascalString) ApplicationIdentityDataTypeBuilder {
	b.Name = name
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) ApplicationIdentityDataTypeBuilder {
	builder := builderSupplier(b.Name.CreatePascalStringBuilder())
	var err error
	b.Name, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithRecordProperties(recordProperties ...KeyValuePair) ApplicationIdentityDataTypeBuilder {
	b.RecordProperties = recordProperties
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithApplicationUri(applicationUri PascalString) ApplicationIdentityDataTypeBuilder {
	b.ApplicationUri = applicationUri
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithApplicationUriBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) ApplicationIdentityDataTypeBuilder {
	builder := builderSupplier(b.ApplicationUri.CreatePascalStringBuilder())
	var err error
	b.ApplicationUri, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithApplicationNames(applicationNames ...LocalizedText) ApplicationIdentityDataTypeBuilder {
	b.ApplicationNames = applicationNames
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) WithAdditionalServers(additionalServers ...ApplicationDescription) ApplicationIdentityDataTypeBuilder {
	b.AdditionalServers = additionalServers
	return b
}

func (b *_ApplicationIdentityDataTypeBuilder) Build() (ApplicationIdentityDataType, error) {
	if b.Name == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'name' not set"))
	}
	if b.ApplicationUri == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'applicationUri' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ApplicationIdentityDataType.deepCopy(), nil
}

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

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

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

func (b *_ApplicationIdentityDataTypeBuilder) DeepCopy() any {
	_copy := b.CreateApplicationIdentityDataTypeBuilder().(*_ApplicationIdentityDataTypeBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateApplicationIdentityDataTypeBuilder creates a ApplicationIdentityDataTypeBuilder
func (b *_ApplicationIdentityDataType) CreateApplicationIdentityDataTypeBuilder() ApplicationIdentityDataTypeBuilder {
	if b == nil {
		return NewApplicationIdentityDataTypeBuilder()
	}
	return &_ApplicationIdentityDataTypeBuilder{_ApplicationIdentityDataType: b.deepCopy()}
}

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

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

func (m *_ApplicationIdentityDataType) GetExtensionId() int32 {
	return int32(15558)
}

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

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

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

func (m *_ApplicationIdentityDataType) GetName() PascalString {
	return m.Name
}

func (m *_ApplicationIdentityDataType) GetRecordProperties() []KeyValuePair {
	return m.RecordProperties
}

func (m *_ApplicationIdentityDataType) GetApplicationUri() PascalString {
	return m.ApplicationUri
}

func (m *_ApplicationIdentityDataType) GetApplicationNames() []LocalizedText {
	return m.ApplicationNames
}

func (m *_ApplicationIdentityDataType) GetAdditionalServers() []ApplicationDescription {
	return m.AdditionalServers
}

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

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

func (m *_ApplicationIdentityDataType) GetTypeName() string {
	return "ApplicationIdentityDataType"
}

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

	// Simple field (name)
	lengthInBits += m.Name.GetLengthInBits(ctx)

	// Implicit Field (noOfRecordProperties)
	lengthInBits += 32

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

	// Simple field (applicationUri)
	lengthInBits += m.ApplicationUri.GetLengthInBits(ctx)

	// Implicit Field (noOfApplicationNames)
	lengthInBits += 32

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

	// Implicit Field (noOfAdditionalServers)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

	recordProperties, err := ReadCountArrayField[KeyValuePair](ctx, "recordProperties", ReadComplex[KeyValuePair](ExtensionObjectDefinitionParseWithBufferProducer[KeyValuePair]((int32)(int32(14535))), readBuffer), uint64(noOfRecordProperties))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'recordProperties' field"))
	}
	m.RecordProperties = recordProperties

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

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

	applicationNames, err := ReadCountArrayField[LocalizedText](ctx, "applicationNames", ReadComplex[LocalizedText](LocalizedTextParseWithBuffer, readBuffer), uint64(noOfApplicationNames))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'applicationNames' field"))
	}
	m.ApplicationNames = applicationNames

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

	additionalServers, err := ReadCountArrayField[ApplicationDescription](ctx, "additionalServers", ReadComplex[ApplicationDescription](ExtensionObjectDefinitionParseWithBufferProducer[ApplicationDescription]((int32)(int32(310))), readBuffer), uint64(noOfAdditionalServers))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'additionalServers' field"))
	}
	m.AdditionalServers = additionalServers

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

	return m, nil
}

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

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

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

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

		if err := WriteComplexTypeArrayField(ctx, "applicationNames", m.GetApplicationNames(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'applicationNames' field")
		}
		noOfAdditionalServers := int32(utils.InlineIf(bool((m.GetAdditionalServers()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetAdditionalServers()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfAdditionalServers", noOfAdditionalServers, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfAdditionalServers' field")
		}

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

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

func (m *_ApplicationIdentityDataType) IsApplicationIdentityDataType() {}

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

func (m *_ApplicationIdentityDataType) deepCopy() *_ApplicationIdentityDataType {
	if m == nil {
		return nil
	}
	_ApplicationIdentityDataTypeCopy := &_ApplicationIdentityDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.Name),
		utils.DeepCopySlice[KeyValuePair, KeyValuePair](m.RecordProperties),
		utils.DeepCopy[PascalString](m.ApplicationUri),
		utils.DeepCopySlice[LocalizedText, LocalizedText](m.ApplicationNames),
		utils.DeepCopySlice[ApplicationDescription, ApplicationDescription](m.AdditionalServers),
	}
	_ApplicationIdentityDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ApplicationIdentityDataTypeCopy
}

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