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

// UpdateStructureDataDetails is the corresponding interface of UpdateStructureDataDetails
type UpdateStructureDataDetails 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
	// IsUpdateStructureDataDetails is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsUpdateStructureDataDetails()
	// CreateBuilder creates a UpdateStructureDataDetailsBuilder
	CreateUpdateStructureDataDetailsBuilder() UpdateStructureDataDetailsBuilder
}

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

var _ UpdateStructureDataDetails = (*_UpdateStructureDataDetails)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_UpdateStructureDataDetails)(nil)

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

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

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

// NewUpdateStructureDataDetailsBuilder() creates a UpdateStructureDataDetailsBuilder
func NewUpdateStructureDataDetailsBuilder() UpdateStructureDataDetailsBuilder {
	return &_UpdateStructureDataDetailsBuilder{_UpdateStructureDataDetails: new(_UpdateStructureDataDetails)}
}

type _UpdateStructureDataDetailsBuilder struct {
	*_UpdateStructureDataDetails

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (UpdateStructureDataDetailsBuilder) = (*_UpdateStructureDataDetailsBuilder)(nil)

func (b *_UpdateStructureDataDetailsBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._UpdateStructureDataDetails
}

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

func (b *_UpdateStructureDataDetailsBuilder) WithNodeId(nodeId NodeId) UpdateStructureDataDetailsBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_UpdateStructureDataDetailsBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) UpdateStructureDataDetailsBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdBuilder())
	var err error
	b.NodeId, 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, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_UpdateStructureDataDetailsBuilder) WithPerformInsertReplace(performInsertReplace PerformUpdateType) UpdateStructureDataDetailsBuilder {
	b.PerformInsertReplace = performInsertReplace
	return b
}

func (b *_UpdateStructureDataDetailsBuilder) WithUpdateValues(updateValues ...DataValue) UpdateStructureDataDetailsBuilder {
	b.UpdateValues = updateValues
	return b
}

func (b *_UpdateStructureDataDetailsBuilder) Build() (UpdateStructureDataDetails, error) {
	if b.NodeId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'nodeId' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._UpdateStructureDataDetails.deepCopy(), nil
}

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

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

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

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

// CreateUpdateStructureDataDetailsBuilder creates a UpdateStructureDataDetailsBuilder
func (b *_UpdateStructureDataDetails) CreateUpdateStructureDataDetailsBuilder() UpdateStructureDataDetailsBuilder {
	if b == nil {
		return NewUpdateStructureDataDetailsBuilder()
	}
	return &_UpdateStructureDataDetailsBuilder{_UpdateStructureDataDetails: b.deepCopy()}
}

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

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

func (m *_UpdateStructureDataDetails) GetExtensionId() int32 {
	return int32(11297)
}

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

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

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

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

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

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

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

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

func (m *_UpdateStructureDataDetails) GetTypeName() string {
	return "UpdateStructureDataDetails"
}

func (m *_UpdateStructureDataDetails) 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 *_UpdateStructureDataDetails) GetLengthInBytes(ctx context.Context) uint16 {
	return m.GetLengthInBits(ctx) / 8
}

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

	return m, nil
}

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

		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("UpdateStructureDataDetails"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for UpdateStructureDataDetails")
		}
		return nil
	}
	return m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_UpdateStructureDataDetails) IsUpdateStructureDataDetails() {}

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

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

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