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

// RegisterNodesRequest is the corresponding interface of RegisterNodesRequest
type RegisterNodesRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetNodesToRegister returns NodesToRegister (property field)
	GetNodesToRegister() []NodeId
	// IsRegisterNodesRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsRegisterNodesRequest()
	// CreateBuilder creates a RegisterNodesRequestBuilder
	CreateRegisterNodesRequestBuilder() RegisterNodesRequestBuilder
}

// _RegisterNodesRequest is the data-structure of this message
type _RegisterNodesRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader   RequestHeader
	NodesToRegister []NodeId
}

var _ RegisterNodesRequest = (*_RegisterNodesRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_RegisterNodesRequest)(nil)

// NewRegisterNodesRequest factory function for _RegisterNodesRequest
func NewRegisterNodesRequest(requestHeader RequestHeader, nodesToRegister []NodeId) *_RegisterNodesRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for RegisterNodesRequest must not be nil")
	}
	_result := &_RegisterNodesRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		NodesToRegister:                   nodesToRegister,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

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

// NewRegisterNodesRequestBuilder() creates a RegisterNodesRequestBuilder
func NewRegisterNodesRequestBuilder() RegisterNodesRequestBuilder {
	return &_RegisterNodesRequestBuilder{_RegisterNodesRequest: new(_RegisterNodesRequest)}
}

type _RegisterNodesRequestBuilder struct {
	*_RegisterNodesRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (RegisterNodesRequestBuilder) = (*_RegisterNodesRequestBuilder)(nil)

func (b *_RegisterNodesRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._RegisterNodesRequest
}

func (b *_RegisterNodesRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, nodesToRegister []NodeId) RegisterNodesRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithNodesToRegister(nodesToRegister...)
}

func (b *_RegisterNodesRequestBuilder) WithRequestHeader(requestHeader RequestHeader) RegisterNodesRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_RegisterNodesRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) RegisterNodesRequestBuilder {
	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 *_RegisterNodesRequestBuilder) WithNodesToRegister(nodesToRegister ...NodeId) RegisterNodesRequestBuilder {
	b.NodesToRegister = nodesToRegister
	return b
}

func (b *_RegisterNodesRequestBuilder) Build() (RegisterNodesRequest, 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._RegisterNodesRequest.deepCopy(), nil
}

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

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

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

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

// CreateRegisterNodesRequestBuilder creates a RegisterNodesRequestBuilder
func (b *_RegisterNodesRequest) CreateRegisterNodesRequestBuilder() RegisterNodesRequestBuilder {
	if b == nil {
		return NewRegisterNodesRequestBuilder()
	}
	return &_RegisterNodesRequestBuilder{_RegisterNodesRequest: b.deepCopy()}
}

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

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

func (m *_RegisterNodesRequest) GetExtensionId() int32 {
	return int32(560)
}

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

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

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

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

func (m *_RegisterNodesRequest) GetNodesToRegister() []NodeId {
	return m.NodesToRegister
}

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

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

func (m *_RegisterNodesRequest) GetTypeName() string {
	return "RegisterNodesRequest"
}

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

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

	// Implicit Field (noOfNodesToRegister)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

	return m, nil
}

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

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

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

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

func (m *_RegisterNodesRequest) IsRegisterNodesRequest() {}

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

func (m *_RegisterNodesRequest) deepCopy() *_RegisterNodesRequest {
	if m == nil {
		return nil
	}
	_RegisterNodesRequestCopy := &_RegisterNodesRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		utils.DeepCopySlice[NodeId, NodeId](m.NodesToRegister),
	}
	_RegisterNodesRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _RegisterNodesRequestCopy
}

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