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

// AddNodesRequest is the corresponding interface of AddNodesRequest
type AddNodesRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetNodesToAdd returns NodesToAdd (property field)
	GetNodesToAdd() []AddNodesItem
	// IsAddNodesRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsAddNodesRequest()
	// CreateBuilder creates a AddNodesRequestBuilder
	CreateAddNodesRequestBuilder() AddNodesRequestBuilder
}

// _AddNodesRequest is the data-structure of this message
type _AddNodesRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader RequestHeader
	NodesToAdd    []AddNodesItem
}

var _ AddNodesRequest = (*_AddNodesRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_AddNodesRequest)(nil)

// NewAddNodesRequest factory function for _AddNodesRequest
func NewAddNodesRequest(requestHeader RequestHeader, nodesToAdd []AddNodesItem) *_AddNodesRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for AddNodesRequest must not be nil")
	}
	_result := &_AddNodesRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		NodesToAdd:                        nodesToAdd,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// AddNodesRequestBuilder is a builder for AddNodesRequest
type AddNodesRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(requestHeader RequestHeader, nodesToAdd []AddNodesItem) AddNodesRequestBuilder
	// WithRequestHeader adds RequestHeader (property field)
	WithRequestHeader(RequestHeader) AddNodesRequestBuilder
	// WithRequestHeaderBuilder adds RequestHeader (property field) which is build by the builder
	WithRequestHeaderBuilder(func(RequestHeaderBuilder) RequestHeaderBuilder) AddNodesRequestBuilder
	// WithNodesToAdd adds NodesToAdd (property field)
	WithNodesToAdd(...AddNodesItem) AddNodesRequestBuilder
	// 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 AddNodesRequest or returns an error if something is wrong
	Build() (AddNodesRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() AddNodesRequest
}

// NewAddNodesRequestBuilder() creates a AddNodesRequestBuilder
func NewAddNodesRequestBuilder() AddNodesRequestBuilder {
	return &_AddNodesRequestBuilder{_AddNodesRequest: new(_AddNodesRequest)}
}

type _AddNodesRequestBuilder struct {
	*_AddNodesRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (AddNodesRequestBuilder) = (*_AddNodesRequestBuilder)(nil)

func (b *_AddNodesRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._AddNodesRequest
}

func (b *_AddNodesRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, nodesToAdd []AddNodesItem) AddNodesRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithNodesToAdd(nodesToAdd...)
}

func (b *_AddNodesRequestBuilder) WithRequestHeader(requestHeader RequestHeader) AddNodesRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_AddNodesRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) AddNodesRequestBuilder {
	builder := builderSupplier(b.RequestHeader.CreateRequestHeaderBuilder())
	var err error
	b.RequestHeader, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "RequestHeaderBuilder failed"))
	}
	return b
}

func (b *_AddNodesRequestBuilder) WithNodesToAdd(nodesToAdd ...AddNodesItem) AddNodesRequestBuilder {
	b.NodesToAdd = nodesToAdd
	return b
}

func (b *_AddNodesRequestBuilder) Build() (AddNodesRequest, error) {
	if b.RequestHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'requestHeader' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._AddNodesRequest.deepCopy(), nil
}

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

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

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

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

// CreateAddNodesRequestBuilder creates a AddNodesRequestBuilder
func (b *_AddNodesRequest) CreateAddNodesRequestBuilder() AddNodesRequestBuilder {
	if b == nil {
		return NewAddNodesRequestBuilder()
	}
	return &_AddNodesRequestBuilder{_AddNodesRequest: b.deepCopy()}
}

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

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

func (m *_AddNodesRequest) GetExtensionId() int32 {
	return int32(488)
}

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

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

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

func (m *_AddNodesRequest) GetRequestHeader() RequestHeader {
	return m.RequestHeader
}

func (m *_AddNodesRequest) GetNodesToAdd() []AddNodesItem {
	return m.NodesToAdd
}

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

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

func (m *_AddNodesRequest) GetTypeName() string {
	return "AddNodesRequest"
}

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

	// Simple field (requestHeader)
	lengthInBits += m.RequestHeader.GetLengthInBits(ctx)

	// Implicit Field (noOfNodesToAdd)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

	requestHeader, err := ReadSimpleField[RequestHeader](ctx, "requestHeader", ReadComplex[RequestHeader](ExtensionObjectDefinitionParseWithBufferProducer[RequestHeader]((int32)(int32(391))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'requestHeader' field"))
	}
	m.RequestHeader = requestHeader

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

	nodesToAdd, err := ReadCountArrayField[AddNodesItem](ctx, "nodesToAdd", ReadComplex[AddNodesItem](ExtensionObjectDefinitionParseWithBufferProducer[AddNodesItem]((int32)(int32(378))), readBuffer), uint64(noOfNodesToAdd))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'nodesToAdd' field"))
	}
	m.NodesToAdd = nodesToAdd

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

	return m, nil
}

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

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

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

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

func (m *_AddNodesRequest) IsAddNodesRequest() {}

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

func (m *_AddNodesRequest) deepCopy() *_AddNodesRequest {
	if m == nil {
		return nil
	}
	_AddNodesRequestCopy := &_AddNodesRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		utils.DeepCopySlice[AddNodesItem, AddNodesItem](m.NodesToAdd),
	}
	_AddNodesRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _AddNodesRequestCopy
}

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