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

// NodeReference is the corresponding interface of NodeReference
type NodeReference interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetReferenceTypeId returns ReferenceTypeId (property field)
	GetReferenceTypeId() NodeId
	// GetIsForward returns IsForward (property field)
	GetIsForward() bool
	// GetReferencedNodeIds returns ReferencedNodeIds (property field)
	GetReferencedNodeIds() []NodeId
	// IsNodeReference is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNodeReference()
	// CreateBuilder creates a NodeReferenceBuilder
	CreateNodeReferenceBuilder() NodeReferenceBuilder
}

// _NodeReference is the data-structure of this message
type _NodeReference struct {
	ExtensionObjectDefinitionContract
	NodeId            NodeId
	ReferenceTypeId   NodeId
	IsForward         bool
	ReferencedNodeIds []NodeId
	// Reserved Fields
	reservedField0 *uint8
}

var _ NodeReference = (*_NodeReference)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_NodeReference)(nil)

// NewNodeReference factory function for _NodeReference
func NewNodeReference(nodeId NodeId, referenceTypeId NodeId, isForward bool, referencedNodeIds []NodeId) *_NodeReference {
	if nodeId == nil {
		panic("nodeId of type NodeId for NodeReference must not be nil")
	}
	if referenceTypeId == nil {
		panic("referenceTypeId of type NodeId for NodeReference must not be nil")
	}
	_result := &_NodeReference{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		ReferenceTypeId:                   referenceTypeId,
		IsForward:                         isForward,
		ReferencedNodeIds:                 referencedNodeIds,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// NodeReferenceBuilder is a builder for NodeReference
type NodeReferenceBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, referenceTypeId NodeId, isForward bool, referencedNodeIds []NodeId) NodeReferenceBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) NodeReferenceBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) NodeReferenceBuilder
	// WithReferenceTypeId adds ReferenceTypeId (property field)
	WithReferenceTypeId(NodeId) NodeReferenceBuilder
	// WithReferenceTypeIdBuilder adds ReferenceTypeId (property field) which is build by the builder
	WithReferenceTypeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) NodeReferenceBuilder
	// WithIsForward adds IsForward (property field)
	WithIsForward(bool) NodeReferenceBuilder
	// WithReferencedNodeIds adds ReferencedNodeIds (property field)
	WithReferencedNodeIds(...NodeId) NodeReferenceBuilder
	// 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 NodeReference or returns an error if something is wrong
	Build() (NodeReference, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NodeReference
}

// NewNodeReferenceBuilder() creates a NodeReferenceBuilder
func NewNodeReferenceBuilder() NodeReferenceBuilder {
	return &_NodeReferenceBuilder{_NodeReference: new(_NodeReference)}
}

type _NodeReferenceBuilder struct {
	*_NodeReference

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (NodeReferenceBuilder) = (*_NodeReferenceBuilder)(nil)

func (b *_NodeReferenceBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._NodeReference
}

func (b *_NodeReferenceBuilder) WithMandatoryFields(nodeId NodeId, referenceTypeId NodeId, isForward bool, referencedNodeIds []NodeId) NodeReferenceBuilder {
	return b.WithNodeId(nodeId).WithReferenceTypeId(referenceTypeId).WithIsForward(isForward).WithReferencedNodeIds(referencedNodeIds...)
}

func (b *_NodeReferenceBuilder) WithNodeId(nodeId NodeId) NodeReferenceBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_NodeReferenceBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) NodeReferenceBuilder {
	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 *_NodeReferenceBuilder) WithReferenceTypeId(referenceTypeId NodeId) NodeReferenceBuilder {
	b.ReferenceTypeId = referenceTypeId
	return b
}

func (b *_NodeReferenceBuilder) WithReferenceTypeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) NodeReferenceBuilder {
	builder := builderSupplier(b.ReferenceTypeId.CreateNodeIdBuilder())
	var err error
	b.ReferenceTypeId, 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 *_NodeReferenceBuilder) WithIsForward(isForward bool) NodeReferenceBuilder {
	b.IsForward = isForward
	return b
}

func (b *_NodeReferenceBuilder) WithReferencedNodeIds(referencedNodeIds ...NodeId) NodeReferenceBuilder {
	b.ReferencedNodeIds = referencedNodeIds
	return b
}

func (b *_NodeReferenceBuilder) Build() (NodeReference, 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.ReferenceTypeId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'referenceTypeId' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._NodeReference.deepCopy(), nil
}

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

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

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

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

// CreateNodeReferenceBuilder creates a NodeReferenceBuilder
func (b *_NodeReference) CreateNodeReferenceBuilder() NodeReferenceBuilder {
	if b == nil {
		return NewNodeReferenceBuilder()
	}
	return &_NodeReferenceBuilder{_NodeReference: b.deepCopy()}
}

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

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

func (m *_NodeReference) GetExtensionId() int32 {
	return int32(582)
}

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

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

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

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

func (m *_NodeReference) GetReferenceTypeId() NodeId {
	return m.ReferenceTypeId
}

func (m *_NodeReference) GetIsForward() bool {
	return m.IsForward
}

func (m *_NodeReference) GetReferencedNodeIds() []NodeId {
	return m.ReferencedNodeIds
}

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

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

func (m *_NodeReference) GetTypeName() string {
	return "NodeReference"
}

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

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

	// Simple field (referenceTypeId)
	lengthInBits += m.ReferenceTypeId.GetLengthInBits(ctx)

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (isForward)
	lengthInBits += 1

	// Implicit Field (noOfReferencedNodeIds)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	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

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

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

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

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

	return m, nil
}

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

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

		if err := WriteSimpleField[NodeId](ctx, "referenceTypeId", m.GetReferenceTypeId(), WriteComplex[NodeId](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'referenceTypeId' 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, "isForward", m.GetIsForward(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'isForward' field")
		}
		noOfReferencedNodeIds := int32(utils.InlineIf(bool((m.GetReferencedNodeIds()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetReferencedNodeIds()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfReferencedNodeIds", noOfReferencedNodeIds, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfReferencedNodeIds' field")
		}

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

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

func (m *_NodeReference) IsNodeReference() {}

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

func (m *_NodeReference) deepCopy() *_NodeReference {
	if m == nil {
		return nil
	}
	_NodeReferenceCopy := &_NodeReference{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		utils.DeepCopy[NodeId](m.ReferenceTypeId),
		m.IsForward,
		utils.DeepCopySlice[NodeId, NodeId](m.ReferencedNodeIds),
		m.reservedField0,
	}
	_NodeReferenceCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _NodeReferenceCopy
}

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