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

// NodeTypeDescription is the corresponding interface of NodeTypeDescription
type NodeTypeDescription interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetTypeDefinitionNode returns TypeDefinitionNode (property field)
	GetTypeDefinitionNode() ExpandedNodeId
	// GetIncludeSubTypes returns IncludeSubTypes (property field)
	GetIncludeSubTypes() bool
	// GetDataToReturn returns DataToReturn (property field)
	GetDataToReturn() []QueryDataDescription
	// IsNodeTypeDescription is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNodeTypeDescription()
	// CreateBuilder creates a NodeTypeDescriptionBuilder
	CreateNodeTypeDescriptionBuilder() NodeTypeDescriptionBuilder
}

// _NodeTypeDescription is the data-structure of this message
type _NodeTypeDescription struct {
	ExtensionObjectDefinitionContract
	TypeDefinitionNode ExpandedNodeId
	IncludeSubTypes    bool
	DataToReturn       []QueryDataDescription
	// Reserved Fields
	reservedField0 *uint8
}

var _ NodeTypeDescription = (*_NodeTypeDescription)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_NodeTypeDescription)(nil)

// NewNodeTypeDescription factory function for _NodeTypeDescription
func NewNodeTypeDescription(typeDefinitionNode ExpandedNodeId, includeSubTypes bool, dataToReturn []QueryDataDescription) *_NodeTypeDescription {
	if typeDefinitionNode == nil {
		panic("typeDefinitionNode of type ExpandedNodeId for NodeTypeDescription must not be nil")
	}
	_result := &_NodeTypeDescription{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		TypeDefinitionNode:                typeDefinitionNode,
		IncludeSubTypes:                   includeSubTypes,
		DataToReturn:                      dataToReturn,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// NodeTypeDescriptionBuilder is a builder for NodeTypeDescription
type NodeTypeDescriptionBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(typeDefinitionNode ExpandedNodeId, includeSubTypes bool, dataToReturn []QueryDataDescription) NodeTypeDescriptionBuilder
	// WithTypeDefinitionNode adds TypeDefinitionNode (property field)
	WithTypeDefinitionNode(ExpandedNodeId) NodeTypeDescriptionBuilder
	// WithTypeDefinitionNodeBuilder adds TypeDefinitionNode (property field) which is build by the builder
	WithTypeDefinitionNodeBuilder(func(ExpandedNodeIdBuilder) ExpandedNodeIdBuilder) NodeTypeDescriptionBuilder
	// WithIncludeSubTypes adds IncludeSubTypes (property field)
	WithIncludeSubTypes(bool) NodeTypeDescriptionBuilder
	// WithDataToReturn adds DataToReturn (property field)
	WithDataToReturn(...QueryDataDescription) NodeTypeDescriptionBuilder
	// 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 NodeTypeDescription or returns an error if something is wrong
	Build() (NodeTypeDescription, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NodeTypeDescription
}

// NewNodeTypeDescriptionBuilder() creates a NodeTypeDescriptionBuilder
func NewNodeTypeDescriptionBuilder() NodeTypeDescriptionBuilder {
	return &_NodeTypeDescriptionBuilder{_NodeTypeDescription: new(_NodeTypeDescription)}
}

type _NodeTypeDescriptionBuilder struct {
	*_NodeTypeDescription

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (NodeTypeDescriptionBuilder) = (*_NodeTypeDescriptionBuilder)(nil)

func (b *_NodeTypeDescriptionBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._NodeTypeDescription
}

func (b *_NodeTypeDescriptionBuilder) WithMandatoryFields(typeDefinitionNode ExpandedNodeId, includeSubTypes bool, dataToReturn []QueryDataDescription) NodeTypeDescriptionBuilder {
	return b.WithTypeDefinitionNode(typeDefinitionNode).WithIncludeSubTypes(includeSubTypes).WithDataToReturn(dataToReturn...)
}

func (b *_NodeTypeDescriptionBuilder) WithTypeDefinitionNode(typeDefinitionNode ExpandedNodeId) NodeTypeDescriptionBuilder {
	b.TypeDefinitionNode = typeDefinitionNode
	return b
}

func (b *_NodeTypeDescriptionBuilder) WithTypeDefinitionNodeBuilder(builderSupplier func(ExpandedNodeIdBuilder) ExpandedNodeIdBuilder) NodeTypeDescriptionBuilder {
	builder := builderSupplier(b.TypeDefinitionNode.CreateExpandedNodeIdBuilder())
	var err error
	b.TypeDefinitionNode, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ExpandedNodeIdBuilder failed"))
	}
	return b
}

func (b *_NodeTypeDescriptionBuilder) WithIncludeSubTypes(includeSubTypes bool) NodeTypeDescriptionBuilder {
	b.IncludeSubTypes = includeSubTypes
	return b
}

func (b *_NodeTypeDescriptionBuilder) WithDataToReturn(dataToReturn ...QueryDataDescription) NodeTypeDescriptionBuilder {
	b.DataToReturn = dataToReturn
	return b
}

func (b *_NodeTypeDescriptionBuilder) Build() (NodeTypeDescription, error) {
	if b.TypeDefinitionNode == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'typeDefinitionNode' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._NodeTypeDescription.deepCopy(), nil
}

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

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

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

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

// CreateNodeTypeDescriptionBuilder creates a NodeTypeDescriptionBuilder
func (b *_NodeTypeDescription) CreateNodeTypeDescriptionBuilder() NodeTypeDescriptionBuilder {
	if b == nil {
		return NewNodeTypeDescriptionBuilder()
	}
	return &_NodeTypeDescriptionBuilder{_NodeTypeDescription: b.deepCopy()}
}

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

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

func (m *_NodeTypeDescription) GetExtensionId() int32 {
	return int32(575)
}

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

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

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

func (m *_NodeTypeDescription) GetTypeDefinitionNode() ExpandedNodeId {
	return m.TypeDefinitionNode
}

func (m *_NodeTypeDescription) GetIncludeSubTypes() bool {
	return m.IncludeSubTypes
}

func (m *_NodeTypeDescription) GetDataToReturn() []QueryDataDescription {
	return m.DataToReturn
}

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

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

func (m *_NodeTypeDescription) GetTypeName() string {
	return "NodeTypeDescription"
}

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

	// Simple field (typeDefinitionNode)
	lengthInBits += m.TypeDefinitionNode.GetLengthInBits(ctx)

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (includeSubTypes)
	lengthInBits += 1

	// Implicit Field (noOfDataToReturn)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(7)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField0 = reservedField0

	includeSubTypes, err := ReadSimpleField(ctx, "includeSubTypes", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'includeSubTypes' field"))
	}
	m.IncludeSubTypes = includeSubTypes

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

	dataToReturn, err := ReadCountArrayField[QueryDataDescription](ctx, "dataToReturn", ReadComplex[QueryDataDescription](ExtensionObjectDefinitionParseWithBufferProducer[QueryDataDescription]((int32)(int32(572))), readBuffer), uint64(noOfDataToReturn))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'dataToReturn' field"))
	}
	m.DataToReturn = dataToReturn

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

	return m, nil
}

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

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

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 7)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 1")
		}

		if err := WriteSimpleField[bool](ctx, "includeSubTypes", m.GetIncludeSubTypes(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'includeSubTypes' field")
		}
		noOfDataToReturn := int32(utils.InlineIf(bool((m.GetDataToReturn()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetDataToReturn()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfDataToReturn", noOfDataToReturn, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfDataToReturn' field")
		}

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

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

func (m *_NodeTypeDescription) IsNodeTypeDescription() {}

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

func (m *_NodeTypeDescription) deepCopy() *_NodeTypeDescription {
	if m == nil {
		return nil
	}
	_NodeTypeDescriptionCopy := &_NodeTypeDescription{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ExpandedNodeId](m.TypeDefinitionNode),
		m.IncludeSubTypes,
		utils.DeepCopySlice[QueryDataDescription, QueryDataDescription](m.DataToReturn),
		m.reservedField0,
	}
	_NodeTypeDescriptionCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _NodeTypeDescriptionCopy
}

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