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

// BaseConfigurationDataType is the corresponding interface of BaseConfigurationDataType
type BaseConfigurationDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetConfigurationVersion returns ConfigurationVersion (property field)
	GetConfigurationVersion() uint32
	// GetConfigurationProperties returns ConfigurationProperties (property field)
	GetConfigurationProperties() []KeyValuePair
	// IsBaseConfigurationDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBaseConfigurationDataType()
	// CreateBuilder creates a BaseConfigurationDataTypeBuilder
	CreateBaseConfigurationDataTypeBuilder() BaseConfigurationDataTypeBuilder
}

// _BaseConfigurationDataType is the data-structure of this message
type _BaseConfigurationDataType struct {
	ExtensionObjectDefinitionContract
	ConfigurationVersion    uint32
	ConfigurationProperties []KeyValuePair
}

var _ BaseConfigurationDataType = (*_BaseConfigurationDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_BaseConfigurationDataType)(nil)

// NewBaseConfigurationDataType factory function for _BaseConfigurationDataType
func NewBaseConfigurationDataType(configurationVersion uint32, configurationProperties []KeyValuePair) *_BaseConfigurationDataType {
	_result := &_BaseConfigurationDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ConfigurationVersion:              configurationVersion,
		ConfigurationProperties:           configurationProperties,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// BaseConfigurationDataTypeBuilder is a builder for BaseConfigurationDataType
type BaseConfigurationDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(configurationVersion uint32, configurationProperties []KeyValuePair) BaseConfigurationDataTypeBuilder
	// WithConfigurationVersion adds ConfigurationVersion (property field)
	WithConfigurationVersion(uint32) BaseConfigurationDataTypeBuilder
	// WithConfigurationProperties adds ConfigurationProperties (property field)
	WithConfigurationProperties(...KeyValuePair) BaseConfigurationDataTypeBuilder
	// 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 BaseConfigurationDataType or returns an error if something is wrong
	Build() (BaseConfigurationDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BaseConfigurationDataType
}

// NewBaseConfigurationDataTypeBuilder() creates a BaseConfigurationDataTypeBuilder
func NewBaseConfigurationDataTypeBuilder() BaseConfigurationDataTypeBuilder {
	return &_BaseConfigurationDataTypeBuilder{_BaseConfigurationDataType: new(_BaseConfigurationDataType)}
}

type _BaseConfigurationDataTypeBuilder struct {
	*_BaseConfigurationDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (BaseConfigurationDataTypeBuilder) = (*_BaseConfigurationDataTypeBuilder)(nil)

func (b *_BaseConfigurationDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._BaseConfigurationDataType
}

func (b *_BaseConfigurationDataTypeBuilder) WithMandatoryFields(configurationVersion uint32, configurationProperties []KeyValuePair) BaseConfigurationDataTypeBuilder {
	return b.WithConfigurationVersion(configurationVersion).WithConfigurationProperties(configurationProperties...)
}

func (b *_BaseConfigurationDataTypeBuilder) WithConfigurationVersion(configurationVersion uint32) BaseConfigurationDataTypeBuilder {
	b.ConfigurationVersion = configurationVersion
	return b
}

func (b *_BaseConfigurationDataTypeBuilder) WithConfigurationProperties(configurationProperties ...KeyValuePair) BaseConfigurationDataTypeBuilder {
	b.ConfigurationProperties = configurationProperties
	return b
}

func (b *_BaseConfigurationDataTypeBuilder) Build() (BaseConfigurationDataType, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._BaseConfigurationDataType.deepCopy(), nil
}

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

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

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

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

// CreateBaseConfigurationDataTypeBuilder creates a BaseConfigurationDataTypeBuilder
func (b *_BaseConfigurationDataType) CreateBaseConfigurationDataTypeBuilder() BaseConfigurationDataTypeBuilder {
	if b == nil {
		return NewBaseConfigurationDataTypeBuilder()
	}
	return &_BaseConfigurationDataTypeBuilder{_BaseConfigurationDataType: b.deepCopy()}
}

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

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

func (m *_BaseConfigurationDataType) GetExtensionId() int32 {
	return int32(15436)
}

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

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

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

func (m *_BaseConfigurationDataType) GetConfigurationVersion() uint32 {
	return m.ConfigurationVersion
}

func (m *_BaseConfigurationDataType) GetConfigurationProperties() []KeyValuePair {
	return m.ConfigurationProperties
}

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

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

func (m *_BaseConfigurationDataType) GetTypeName() string {
	return "BaseConfigurationDataType"
}

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

	// Simple field (configurationVersion)
	lengthInBits += 32

	// Implicit Field (noOfConfigurationProperties)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

	return m, nil
}

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

		if err := WriteSimpleField[uint32](ctx, "configurationVersion", m.GetConfigurationVersion(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'configurationVersion' field")
		}
		noOfConfigurationProperties := int32(utils.InlineIf(bool((m.GetConfigurationProperties()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetConfigurationProperties()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfConfigurationProperties", noOfConfigurationProperties, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfConfigurationProperties' field")
		}

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

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

func (m *_BaseConfigurationDataType) IsBaseConfigurationDataType() {}

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

func (m *_BaseConfigurationDataType) deepCopy() *_BaseConfigurationDataType {
	if m == nil {
		return nil
	}
	_BaseConfigurationDataTypeCopy := &_BaseConfigurationDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.ConfigurationVersion,
		utils.DeepCopySlice[KeyValuePair, KeyValuePair](m.ConfigurationProperties),
	}
	_BaseConfigurationDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _BaseConfigurationDataTypeCopy
}

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