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

// PortableNodeId is the corresponding interface of PortableNodeId
type PortableNodeId interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNamespaceUri returns NamespaceUri (property field)
	GetNamespaceUri() PascalString
	// GetIdentifier returns Identifier (property field)
	GetIdentifier() NodeId
	// IsPortableNodeId is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsPortableNodeId()
	// CreateBuilder creates a PortableNodeIdBuilder
	CreatePortableNodeIdBuilder() PortableNodeIdBuilder
}

// _PortableNodeId is the data-structure of this message
type _PortableNodeId struct {
	ExtensionObjectDefinitionContract
	NamespaceUri PascalString
	Identifier   NodeId
}

var _ PortableNodeId = (*_PortableNodeId)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_PortableNodeId)(nil)

// NewPortableNodeId factory function for _PortableNodeId
func NewPortableNodeId(namespaceUri PascalString, identifier NodeId) *_PortableNodeId {
	if namespaceUri == nil {
		panic("namespaceUri of type PascalString for PortableNodeId must not be nil")
	}
	if identifier == nil {
		panic("identifier of type NodeId for PortableNodeId must not be nil")
	}
	_result := &_PortableNodeId{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NamespaceUri:                      namespaceUri,
		Identifier:                        identifier,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// PortableNodeIdBuilder is a builder for PortableNodeId
type PortableNodeIdBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(namespaceUri PascalString, identifier NodeId) PortableNodeIdBuilder
	// WithNamespaceUri adds NamespaceUri (property field)
	WithNamespaceUri(PascalString) PortableNodeIdBuilder
	// WithNamespaceUriBuilder adds NamespaceUri (property field) which is build by the builder
	WithNamespaceUriBuilder(func(PascalStringBuilder) PascalStringBuilder) PortableNodeIdBuilder
	// WithIdentifier adds Identifier (property field)
	WithIdentifier(NodeId) PortableNodeIdBuilder
	// WithIdentifierBuilder adds Identifier (property field) which is build by the builder
	WithIdentifierBuilder(func(NodeIdBuilder) NodeIdBuilder) PortableNodeIdBuilder
	// 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 PortableNodeId or returns an error if something is wrong
	Build() (PortableNodeId, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() PortableNodeId
}

// NewPortableNodeIdBuilder() creates a PortableNodeIdBuilder
func NewPortableNodeIdBuilder() PortableNodeIdBuilder {
	return &_PortableNodeIdBuilder{_PortableNodeId: new(_PortableNodeId)}
}

type _PortableNodeIdBuilder struct {
	*_PortableNodeId

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (PortableNodeIdBuilder) = (*_PortableNodeIdBuilder)(nil)

func (b *_PortableNodeIdBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._PortableNodeId
}

func (b *_PortableNodeIdBuilder) WithMandatoryFields(namespaceUri PascalString, identifier NodeId) PortableNodeIdBuilder {
	return b.WithNamespaceUri(namespaceUri).WithIdentifier(identifier)
}

func (b *_PortableNodeIdBuilder) WithNamespaceUri(namespaceUri PascalString) PortableNodeIdBuilder {
	b.NamespaceUri = namespaceUri
	return b
}

func (b *_PortableNodeIdBuilder) WithNamespaceUriBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) PortableNodeIdBuilder {
	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 *_PortableNodeIdBuilder) WithIdentifier(identifier NodeId) PortableNodeIdBuilder {
	b.Identifier = identifier
	return b
}

func (b *_PortableNodeIdBuilder) WithIdentifierBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) PortableNodeIdBuilder {
	builder := builderSupplier(b.Identifier.CreateNodeIdBuilder())
	var err error
	b.Identifier, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_PortableNodeIdBuilder) Build() (PortableNodeId, error) {
	if b.NamespaceUri == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'namespaceUri' not set"))
	}
	if b.Identifier == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'identifier' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._PortableNodeId.deepCopy(), nil
}

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

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

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

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

// CreatePortableNodeIdBuilder creates a PortableNodeIdBuilder
func (b *_PortableNodeId) CreatePortableNodeIdBuilder() PortableNodeIdBuilder {
	if b == nil {
		return NewPortableNodeIdBuilder()
	}
	return &_PortableNodeIdBuilder{_PortableNodeId: b.deepCopy()}
}

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

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

func (m *_PortableNodeId) GetExtensionId() int32 {
	return int32(24108)
}

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

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

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

func (m *_PortableNodeId) GetNamespaceUri() PascalString {
	return m.NamespaceUri
}

func (m *_PortableNodeId) GetIdentifier() NodeId {
	return m.Identifier
}

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

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

func (m *_PortableNodeId) GetTypeName() string {
	return "PortableNodeId"
}

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

	// Simple field (namespaceUri)
	lengthInBits += m.NamespaceUri.GetLengthInBits(ctx)

	// Simple field (identifier)
	lengthInBits += m.Identifier.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	namespaceUri, err := ReadSimpleField[PascalString](ctx, "namespaceUri", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'namespaceUri' field"))
	}
	m.NamespaceUri = namespaceUri

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

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

	return m, nil
}

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

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

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

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

func (m *_PortableNodeId) IsPortableNodeId() {}

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

func (m *_PortableNodeId) deepCopy() *_PortableNodeId {
	if m == nil {
		return nil
	}
	_PortableNodeIdCopy := &_PortableNodeId{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.NamespaceUri),
		utils.DeepCopy[NodeId](m.Identifier),
	}
	_PortableNodeIdCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _PortableNodeIdCopy
}

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