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

// UpdateDataDetails is the corresponding interface of UpdateDataDetails
type UpdateDataDetails interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetPerformInsertReplace returns PerformInsertReplace (property field)
	GetPerformInsertReplace() PerformUpdateType
	// GetUpdateValues returns UpdateValues (property field)
	GetUpdateValues() []DataValue
	// IsUpdateDataDetails is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsUpdateDataDetails()
	// CreateBuilder creates a UpdateDataDetailsBuilder
	CreateUpdateDataDetailsBuilder() UpdateDataDetailsBuilder
}

// _UpdateDataDetails is the data-structure of this message
type _UpdateDataDetails struct {
	ExtensionObjectDefinitionContract
	NodeId               NodeId
	PerformInsertReplace PerformUpdateType
	UpdateValues         []DataValue
}

var _ UpdateDataDetails = (*_UpdateDataDetails)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_UpdateDataDetails)(nil)

// NewUpdateDataDetails factory function for _UpdateDataDetails
func NewUpdateDataDetails(nodeId NodeId, performInsertReplace PerformUpdateType, updateValues []DataValue) *_UpdateDataDetails {
	if nodeId == nil {
		panic("nodeId of type NodeId for UpdateDataDetails must not be nil")
	}
	_result := &_UpdateDataDetails{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		PerformInsertReplace:              performInsertReplace,
		UpdateValues:                      updateValues,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// UpdateDataDetailsBuilder is a builder for UpdateDataDetails
type UpdateDataDetailsBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, performInsertReplace PerformUpdateType, updateValues []DataValue) UpdateDataDetailsBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) UpdateDataDetailsBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) UpdateDataDetailsBuilder
	// WithPerformInsertReplace adds PerformInsertReplace (property field)
	WithPerformInsertReplace(PerformUpdateType) UpdateDataDetailsBuilder
	// WithUpdateValues adds UpdateValues (property field)
	WithUpdateValues(...DataValue) UpdateDataDetailsBuilder
	// 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 UpdateDataDetails or returns an error if something is wrong
	Build() (UpdateDataDetails, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() UpdateDataDetails
}

// NewUpdateDataDetailsBuilder() creates a UpdateDataDetailsBuilder
func NewUpdateDataDetailsBuilder() UpdateDataDetailsBuilder {
	return &_UpdateDataDetailsBuilder{_UpdateDataDetails: new(_UpdateDataDetails)}
}

type _UpdateDataDetailsBuilder struct {
	*_UpdateDataDetails

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (UpdateDataDetailsBuilder) = (*_UpdateDataDetailsBuilder)(nil)

func (b *_UpdateDataDetailsBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._UpdateDataDetails
}

func (b *_UpdateDataDetailsBuilder) WithMandatoryFields(nodeId NodeId, performInsertReplace PerformUpdateType, updateValues []DataValue) UpdateDataDetailsBuilder {
	return b.WithNodeId(nodeId).WithPerformInsertReplace(performInsertReplace).WithUpdateValues(updateValues...)
}

func (b *_UpdateDataDetailsBuilder) WithNodeId(nodeId NodeId) UpdateDataDetailsBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_UpdateDataDetailsBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) UpdateDataDetailsBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdBuilder())
	var err error
	b.NodeId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_UpdateDataDetailsBuilder) WithPerformInsertReplace(performInsertReplace PerformUpdateType) UpdateDataDetailsBuilder {
	b.PerformInsertReplace = performInsertReplace
	return b
}

func (b *_UpdateDataDetailsBuilder) WithUpdateValues(updateValues ...DataValue) UpdateDataDetailsBuilder {
	b.UpdateValues = updateValues
	return b
}

func (b *_UpdateDataDetailsBuilder) Build() (UpdateDataDetails, error) {
	if b.NodeId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'nodeId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._UpdateDataDetails.deepCopy(), nil
}

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

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

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

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

// CreateUpdateDataDetailsBuilder creates a UpdateDataDetailsBuilder
func (b *_UpdateDataDetails) CreateUpdateDataDetailsBuilder() UpdateDataDetailsBuilder {
	if b == nil {
		return NewUpdateDataDetailsBuilder()
	}
	return &_UpdateDataDetailsBuilder{_UpdateDataDetails: b.deepCopy()}
}

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

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

func (m *_UpdateDataDetails) GetExtensionId() int32 {
	return int32(682)
}

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

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

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

func (m *_UpdateDataDetails) GetNodeId() NodeId {
	return m.NodeId
}

func (m *_UpdateDataDetails) GetPerformInsertReplace() PerformUpdateType {
	return m.PerformInsertReplace
}

func (m *_UpdateDataDetails) GetUpdateValues() []DataValue {
	return m.UpdateValues
}

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

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

func (m *_UpdateDataDetails) GetTypeName() string {
	return "UpdateDataDetails"
}

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

	// Simple field (nodeId)
	lengthInBits += m.NodeId.GetLengthInBits(ctx)

	// Simple field (performInsertReplace)
	lengthInBits += 32

	// Implicit Field (noOfUpdateValues)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	performInsertReplace, err := ReadEnumField[PerformUpdateType](ctx, "performInsertReplace", "PerformUpdateType", ReadEnum(PerformUpdateTypeByValue, ReadUnsignedInt(readBuffer, uint8(32))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'performInsertReplace' field"))
	}
	m.PerformInsertReplace = performInsertReplace

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

	updateValues, err := ReadCountArrayField[DataValue](ctx, "updateValues", ReadComplex[DataValue](DataValueParseWithBuffer, readBuffer), uint64(noOfUpdateValues))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'updateValues' field"))
	}
	m.UpdateValues = updateValues

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

	return m, nil
}

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

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

		if err := WriteSimpleEnumField[PerformUpdateType](ctx, "performInsertReplace", "PerformUpdateType", m.GetPerformInsertReplace(), WriteEnum[PerformUpdateType, uint32](PerformUpdateType.GetValue, PerformUpdateType.PLC4XEnumName, WriteUnsignedInt(writeBuffer, 32))); err != nil {
			return errors.Wrap(err, "Error serializing 'performInsertReplace' field")
		}
		noOfUpdateValues := int32(utils.InlineIf(bool((m.GetUpdateValues()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetUpdateValues()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfUpdateValues", noOfUpdateValues, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfUpdateValues' field")
		}

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

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

func (m *_UpdateDataDetails) IsUpdateDataDetails() {}

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

func (m *_UpdateDataDetails) deepCopy() *_UpdateDataDetails {
	if m == nil {
		return nil
	}
	_UpdateDataDetailsCopy := &_UpdateDataDetails{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		m.PerformInsertReplace,
		utils.DeepCopySlice[DataValue, DataValue](m.UpdateValues),
	}
	_UpdateDataDetailsCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _UpdateDataDetailsCopy
}

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