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

// ExpandedNodeId is the corresponding interface of ExpandedNodeId
type ExpandedNodeId interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetNamespaceURISpecified returns NamespaceURISpecified (property field)
	GetNamespaceURISpecified() bool
	// GetServerIndexSpecified returns ServerIndexSpecified (property field)
	GetServerIndexSpecified() bool
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeIdTypeDefinition
	// GetNamespaceURI returns NamespaceURI (property field)
	GetNamespaceURI() PascalString
	// GetServerIndex returns ServerIndex (property field)
	GetServerIndex() *uint32
	// IsExpandedNodeId is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsExpandedNodeId()
	// CreateBuilder creates a ExpandedNodeIdBuilder
	CreateExpandedNodeIdBuilder() ExpandedNodeIdBuilder
}

// _ExpandedNodeId is the data-structure of this message
type _ExpandedNodeId struct {
	NamespaceURISpecified bool
	ServerIndexSpecified  bool
	NodeId                NodeIdTypeDefinition
	NamespaceURI          PascalString
	ServerIndex           *uint32
}

var _ ExpandedNodeId = (*_ExpandedNodeId)(nil)

// NewExpandedNodeId factory function for _ExpandedNodeId
func NewExpandedNodeId(namespaceURISpecified bool, serverIndexSpecified bool, nodeId NodeIdTypeDefinition, namespaceURI PascalString, serverIndex *uint32) *_ExpandedNodeId {
	if nodeId == nil {
		panic("nodeId of type NodeIdTypeDefinition for ExpandedNodeId must not be nil")
	}
	return &_ExpandedNodeId{NamespaceURISpecified: namespaceURISpecified, ServerIndexSpecified: serverIndexSpecified, NodeId: nodeId, NamespaceURI: namespaceURI, ServerIndex: serverIndex}
}

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

// ExpandedNodeIdBuilder is a builder for ExpandedNodeId
type ExpandedNodeIdBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(namespaceURISpecified bool, serverIndexSpecified bool, nodeId NodeIdTypeDefinition) ExpandedNodeIdBuilder
	// WithNamespaceURISpecified adds NamespaceURISpecified (property field)
	WithNamespaceURISpecified(bool) ExpandedNodeIdBuilder
	// WithServerIndexSpecified adds ServerIndexSpecified (property field)
	WithServerIndexSpecified(bool) ExpandedNodeIdBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeIdTypeDefinition) ExpandedNodeIdBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdTypeDefinitionBuilder) NodeIdTypeDefinitionBuilder) ExpandedNodeIdBuilder
	// WithNamespaceURI adds NamespaceURI (property field)
	WithOptionalNamespaceURI(PascalString) ExpandedNodeIdBuilder
	// WithOptionalNamespaceURIBuilder adds NamespaceURI (property field) which is build by the builder
	WithOptionalNamespaceURIBuilder(func(PascalStringBuilder) PascalStringBuilder) ExpandedNodeIdBuilder
	// WithServerIndex adds ServerIndex (property field)
	WithOptionalServerIndex(uint32) ExpandedNodeIdBuilder
	// Build builds the ExpandedNodeId or returns an error if something is wrong
	Build() (ExpandedNodeId, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ExpandedNodeId
}

// NewExpandedNodeIdBuilder() creates a ExpandedNodeIdBuilder
func NewExpandedNodeIdBuilder() ExpandedNodeIdBuilder {
	return &_ExpandedNodeIdBuilder{_ExpandedNodeId: new(_ExpandedNodeId)}
}

type _ExpandedNodeIdBuilder struct {
	*_ExpandedNodeId

	collectedErr []error
}

var _ (ExpandedNodeIdBuilder) = (*_ExpandedNodeIdBuilder)(nil)

func (b *_ExpandedNodeIdBuilder) WithMandatoryFields(namespaceURISpecified bool, serverIndexSpecified bool, nodeId NodeIdTypeDefinition) ExpandedNodeIdBuilder {
	return b.WithNamespaceURISpecified(namespaceURISpecified).WithServerIndexSpecified(serverIndexSpecified).WithNodeId(nodeId)
}

func (b *_ExpandedNodeIdBuilder) WithNamespaceURISpecified(namespaceURISpecified bool) ExpandedNodeIdBuilder {
	b.NamespaceURISpecified = namespaceURISpecified
	return b
}

func (b *_ExpandedNodeIdBuilder) WithServerIndexSpecified(serverIndexSpecified bool) ExpandedNodeIdBuilder {
	b.ServerIndexSpecified = serverIndexSpecified
	return b
}

func (b *_ExpandedNodeIdBuilder) WithNodeId(nodeId NodeIdTypeDefinition) ExpandedNodeIdBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_ExpandedNodeIdBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdTypeDefinitionBuilder) NodeIdTypeDefinitionBuilder) ExpandedNodeIdBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdTypeDefinitionBuilder())
	var err error
	b.NodeId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdTypeDefinitionBuilder failed"))
	}
	return b
}

func (b *_ExpandedNodeIdBuilder) WithOptionalNamespaceURI(namespaceURI PascalString) ExpandedNodeIdBuilder {
	b.NamespaceURI = namespaceURI
	return b
}

func (b *_ExpandedNodeIdBuilder) WithOptionalNamespaceURIBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) ExpandedNodeIdBuilder {
	builder := builderSupplier(b.NamespaceURI.CreatePascalStringBuilder())
	var err error
	b.NamespaceURI, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_ExpandedNodeIdBuilder) WithOptionalServerIndex(serverIndex uint32) ExpandedNodeIdBuilder {
	b.ServerIndex = &serverIndex
	return b
}

func (b *_ExpandedNodeIdBuilder) Build() (ExpandedNodeId, error) {
	if b.NodeId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'nodeId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ExpandedNodeId.deepCopy(), nil
}

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

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

// CreateExpandedNodeIdBuilder creates a ExpandedNodeIdBuilder
func (b *_ExpandedNodeId) CreateExpandedNodeIdBuilder() ExpandedNodeIdBuilder {
	if b == nil {
		return NewExpandedNodeIdBuilder()
	}
	return &_ExpandedNodeIdBuilder{_ExpandedNodeId: b.deepCopy()}
}

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

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

func (m *_ExpandedNodeId) GetNamespaceURISpecified() bool {
	return m.NamespaceURISpecified
}

func (m *_ExpandedNodeId) GetServerIndexSpecified() bool {
	return m.ServerIndexSpecified
}

func (m *_ExpandedNodeId) GetNodeId() NodeIdTypeDefinition {
	return m.NodeId
}

func (m *_ExpandedNodeId) GetNamespaceURI() PascalString {
	return m.NamespaceURI
}

func (m *_ExpandedNodeId) GetServerIndex() *uint32 {
	return m.ServerIndex
}

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

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

func (m *_ExpandedNodeId) GetTypeName() string {
	return "ExpandedNodeId"
}

func (m *_ExpandedNodeId) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (namespaceURISpecified)
	lengthInBits += 1

	// Simple field (serverIndexSpecified)
	lengthInBits += 1

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

	// Optional Field (namespaceURI)
	if m.NamespaceURI != nil {
		lengthInBits += m.NamespaceURI.GetLengthInBits(ctx)
	}

	// Optional Field (serverIndex)
	if m.ServerIndex != nil {
		lengthInBits += 32
	}

	return lengthInBits
}

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

func ExpandedNodeIdParse(ctx context.Context, theBytes []byte) (ExpandedNodeId, error) {
	return ExpandedNodeIdParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func ExpandedNodeIdParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (ExpandedNodeId, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (ExpandedNodeId, error) {
		return ExpandedNodeIdParseWithBuffer(ctx, readBuffer)
	}
}

func ExpandedNodeIdParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer) (ExpandedNodeId, error) {
	v, err := (new(_ExpandedNodeId)).parse(ctx, readBuffer)
	if err != nil {
		return nil, err
	}
	return v, nil
}

func (m *_ExpandedNodeId) parse(ctx context.Context, readBuffer utils.ReadBuffer) (__expandedNodeId ExpandedNodeId, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ExpandedNodeId"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ExpandedNodeId")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

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

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

	var namespaceURI PascalString
	_namespaceURI, err := ReadOptionalField[PascalString](ctx, "namespaceURI", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer), namespaceURISpecified)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'namespaceURI' field"))
	}
	if _namespaceURI != nil {
		namespaceURI = *_namespaceURI
		m.NamespaceURI = namespaceURI
	}

	var serverIndex *uint32
	serverIndex, err = ReadOptionalField[uint32](ctx, "serverIndex", ReadUnsignedInt(readBuffer, uint8(32)), serverIndexSpecified)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serverIndex' field"))
	}
	m.ServerIndex = serverIndex

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

	return m, nil
}

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

	if err := WriteSimpleField[bool](ctx, "namespaceURISpecified", m.GetNamespaceURISpecified(), WriteBoolean(writeBuffer)); err != nil {
		return errors.Wrap(err, "Error serializing 'namespaceURISpecified' field")
	}

	if err := WriteSimpleField[bool](ctx, "serverIndexSpecified", m.GetServerIndexSpecified(), WriteBoolean(writeBuffer)); err != nil {
		return errors.Wrap(err, "Error serializing 'serverIndexSpecified' field")
	}

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

	if err := WriteOptionalField[PascalString](ctx, "namespaceURI", GetRef(m.GetNamespaceURI()), WriteComplex[PascalString](writeBuffer), true); err != nil {
		return errors.Wrap(err, "Error serializing 'namespaceURI' field")
	}

	if err := WriteOptionalField[uint32](ctx, "serverIndex", m.GetServerIndex(), WriteUnsignedInt(writeBuffer, 32), true); err != nil {
		return errors.Wrap(err, "Error serializing 'serverIndex' field")
	}

	if popErr := writeBuffer.PopContext("ExpandedNodeId"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for ExpandedNodeId")
	}
	return nil
}

func (m *_ExpandedNodeId) IsExpandedNodeId() {}

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

func (m *_ExpandedNodeId) deepCopy() *_ExpandedNodeId {
	if m == nil {
		return nil
	}
	_ExpandedNodeIdCopy := &_ExpandedNodeId{
		m.NamespaceURISpecified,
		m.ServerIndexSpecified,
		utils.DeepCopy[NodeIdTypeDefinition](m.NodeId),
		utils.DeepCopy[PascalString](m.NamespaceURI),
		utils.CopyPtr[uint32](m.ServerIndex),
	}
	return _ExpandedNodeIdCopy
}

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