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

// SecuritySettingsDataType is the corresponding interface of SecuritySettingsDataType
type SecuritySettingsDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetName returns Name (property field)
	GetName() PascalString
	// GetRecordProperties returns RecordProperties (property field)
	GetRecordProperties() []KeyValuePair
	// GetSecurityModes returns SecurityModes (property field)
	GetSecurityModes() []MessageSecurityMode
	// GetSecurityPolicyUris returns SecurityPolicyUris (property field)
	GetSecurityPolicyUris() []PascalString
	// GetCertificateGroupName returns CertificateGroupName (property field)
	GetCertificateGroupName() PascalString
	// IsSecuritySettingsDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsSecuritySettingsDataType()
	// CreateBuilder creates a SecuritySettingsDataTypeBuilder
	CreateSecuritySettingsDataTypeBuilder() SecuritySettingsDataTypeBuilder
}

// _SecuritySettingsDataType is the data-structure of this message
type _SecuritySettingsDataType struct {
	ExtensionObjectDefinitionContract
	Name                 PascalString
	RecordProperties     []KeyValuePair
	SecurityModes        []MessageSecurityMode
	SecurityPolicyUris   []PascalString
	CertificateGroupName PascalString
}

var _ SecuritySettingsDataType = (*_SecuritySettingsDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_SecuritySettingsDataType)(nil)

// NewSecuritySettingsDataType factory function for _SecuritySettingsDataType
func NewSecuritySettingsDataType(name PascalString, recordProperties []KeyValuePair, securityModes []MessageSecurityMode, securityPolicyUris []PascalString, certificateGroupName PascalString) *_SecuritySettingsDataType {
	if name == nil {
		panic("name of type PascalString for SecuritySettingsDataType must not be nil")
	}
	if certificateGroupName == nil {
		panic("certificateGroupName of type PascalString for SecuritySettingsDataType must not be nil")
	}
	_result := &_SecuritySettingsDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Name:                              name,
		RecordProperties:                  recordProperties,
		SecurityModes:                     securityModes,
		SecurityPolicyUris:                securityPolicyUris,
		CertificateGroupName:              certificateGroupName,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// SecuritySettingsDataTypeBuilder is a builder for SecuritySettingsDataType
type SecuritySettingsDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, securityModes []MessageSecurityMode, securityPolicyUris []PascalString, certificateGroupName PascalString) SecuritySettingsDataTypeBuilder
	// WithName adds Name (property field)
	WithName(PascalString) SecuritySettingsDataTypeBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) SecuritySettingsDataTypeBuilder
	// WithRecordProperties adds RecordProperties (property field)
	WithRecordProperties(...KeyValuePair) SecuritySettingsDataTypeBuilder
	// WithSecurityModes adds SecurityModes (property field)
	WithSecurityModes(...MessageSecurityMode) SecuritySettingsDataTypeBuilder
	// WithSecurityPolicyUris adds SecurityPolicyUris (property field)
	WithSecurityPolicyUris(...PascalString) SecuritySettingsDataTypeBuilder
	// WithCertificateGroupName adds CertificateGroupName (property field)
	WithCertificateGroupName(PascalString) SecuritySettingsDataTypeBuilder
	// WithCertificateGroupNameBuilder adds CertificateGroupName (property field) which is build by the builder
	WithCertificateGroupNameBuilder(func(PascalStringBuilder) PascalStringBuilder) SecuritySettingsDataTypeBuilder
	// 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 SecuritySettingsDataType or returns an error if something is wrong
	Build() (SecuritySettingsDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() SecuritySettingsDataType
}

// NewSecuritySettingsDataTypeBuilder() creates a SecuritySettingsDataTypeBuilder
func NewSecuritySettingsDataTypeBuilder() SecuritySettingsDataTypeBuilder {
	return &_SecuritySettingsDataTypeBuilder{_SecuritySettingsDataType: new(_SecuritySettingsDataType)}
}

type _SecuritySettingsDataTypeBuilder struct {
	*_SecuritySettingsDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (SecuritySettingsDataTypeBuilder) = (*_SecuritySettingsDataTypeBuilder)(nil)

func (b *_SecuritySettingsDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._SecuritySettingsDataType
}

func (b *_SecuritySettingsDataTypeBuilder) WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, securityModes []MessageSecurityMode, securityPolicyUris []PascalString, certificateGroupName PascalString) SecuritySettingsDataTypeBuilder {
	return b.WithName(name).WithRecordProperties(recordProperties...).WithSecurityModes(securityModes...).WithSecurityPolicyUris(securityPolicyUris...).WithCertificateGroupName(certificateGroupName)
}

func (b *_SecuritySettingsDataTypeBuilder) WithName(name PascalString) SecuritySettingsDataTypeBuilder {
	b.Name = name
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) SecuritySettingsDataTypeBuilder {
	builder := builderSupplier(b.Name.CreatePascalStringBuilder())
	var err error
	b.Name, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithRecordProperties(recordProperties ...KeyValuePair) SecuritySettingsDataTypeBuilder {
	b.RecordProperties = recordProperties
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithSecurityModes(securityModes ...MessageSecurityMode) SecuritySettingsDataTypeBuilder {
	b.SecurityModes = securityModes
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithSecurityPolicyUris(securityPolicyUris ...PascalString) SecuritySettingsDataTypeBuilder {
	b.SecurityPolicyUris = securityPolicyUris
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithCertificateGroupName(certificateGroupName PascalString) SecuritySettingsDataTypeBuilder {
	b.CertificateGroupName = certificateGroupName
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) WithCertificateGroupNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) SecuritySettingsDataTypeBuilder {
	builder := builderSupplier(b.CertificateGroupName.CreatePascalStringBuilder())
	var err error
	b.CertificateGroupName, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_SecuritySettingsDataTypeBuilder) Build() (SecuritySettingsDataType, error) {
	if b.Name == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'name' not set"))
	}
	if b.CertificateGroupName == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'certificateGroupName' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._SecuritySettingsDataType.deepCopy(), nil
}

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

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

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

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

// CreateSecuritySettingsDataTypeBuilder creates a SecuritySettingsDataTypeBuilder
func (b *_SecuritySettingsDataType) CreateSecuritySettingsDataTypeBuilder() SecuritySettingsDataTypeBuilder {
	if b == nil {
		return NewSecuritySettingsDataTypeBuilder()
	}
	return &_SecuritySettingsDataTypeBuilder{_SecuritySettingsDataType: b.deepCopy()}
}

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

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

func (m *_SecuritySettingsDataType) GetExtensionId() int32 {
	return int32(15561)
}

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

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

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

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

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

func (m *_SecuritySettingsDataType) GetSecurityModes() []MessageSecurityMode {
	return m.SecurityModes
}

func (m *_SecuritySettingsDataType) GetSecurityPolicyUris() []PascalString {
	return m.SecurityPolicyUris
}

func (m *_SecuritySettingsDataType) GetCertificateGroupName() PascalString {
	return m.CertificateGroupName
}

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

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

func (m *_SecuritySettingsDataType) GetTypeName() string {
	return "SecuritySettingsDataType"
}

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

	// Implicit Field (noOfSecurityModes)
	lengthInBits += 32

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

	// Implicit Field (noOfSecurityPolicyUris)
	lengthInBits += 32

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

	// Simple field (certificateGroupName)
	lengthInBits += m.CertificateGroupName.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_SecuritySettingsDataType) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__securitySettingsDataType SecuritySettingsDataType, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("SecuritySettingsDataType"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for SecuritySettingsDataType")
	}
	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

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

	securityModes, err := ReadCountArrayField[MessageSecurityMode](ctx, "securityModes", ReadEnum(MessageSecurityModeByValue, ReadUnsignedInt(readBuffer, uint8(32))), uint64(noOfSecurityModes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'securityModes' field"))
	}
	m.SecurityModes = securityModes

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

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

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

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

	return m, nil
}

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

		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")
		}
		noOfSecurityModes := int32(utils.InlineIf(bool((m.GetSecurityModes()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetSecurityModes()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfSecurityModes", noOfSecurityModes, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfSecurityModes' field")
		}

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

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

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

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

func (m *_SecuritySettingsDataType) IsSecuritySettingsDataType() {}

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

func (m *_SecuritySettingsDataType) deepCopy() *_SecuritySettingsDataType {
	if m == nil {
		return nil
	}
	_SecuritySettingsDataTypeCopy := &_SecuritySettingsDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.Name),
		utils.DeepCopySlice[KeyValuePair, KeyValuePair](m.RecordProperties),
		utils.DeepCopySlice[MessageSecurityMode, MessageSecurityMode](m.SecurityModes),
		utils.DeepCopySlice[PascalString, PascalString](m.SecurityPolicyUris),
		utils.DeepCopy[PascalString](m.CertificateGroupName),
	}
	_SecuritySettingsDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _SecuritySettingsDataTypeCopy
}

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