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

// NodeIdGuid is the corresponding interface of NodeIdGuid
type NodeIdGuid interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	NodeIdTypeDefinition
	// GetNamespaceIndex returns NamespaceIndex (property field)
	GetNamespaceIndex() uint16
	// GetId returns Id (property field)
	GetId() []byte
	// GetIdentifier returns Identifier (virtual field)
	GetIdentifier() string
	// GetNamespace returns Namespace (virtual field)
	GetNamespace() int16
	// IsNodeIdGuid is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNodeIdGuid()
	// CreateBuilder creates a NodeIdGuidBuilder
	CreateNodeIdGuidBuilder() NodeIdGuidBuilder
}

// _NodeIdGuid is the data-structure of this message
type _NodeIdGuid struct {
	NodeIdTypeDefinitionContract
	NamespaceIndex uint16
	Id             []byte
}

var _ NodeIdGuid = (*_NodeIdGuid)(nil)
var _ NodeIdTypeDefinitionRequirements = (*_NodeIdGuid)(nil)

// NewNodeIdGuid factory function for _NodeIdGuid
func NewNodeIdGuid(namespaceIndex uint16, id []byte) *_NodeIdGuid {
	_result := &_NodeIdGuid{
		NodeIdTypeDefinitionContract: NewNodeIdTypeDefinition(),
		NamespaceIndex:               namespaceIndex,
		Id:                           id,
	}
	_result.NodeIdTypeDefinitionContract.(*_NodeIdTypeDefinition)._SubType = _result
	return _result
}

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

// NodeIdGuidBuilder is a builder for NodeIdGuid
type NodeIdGuidBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(namespaceIndex uint16, id []byte) NodeIdGuidBuilder
	// WithNamespaceIndex adds NamespaceIndex (property field)
	WithNamespaceIndex(uint16) NodeIdGuidBuilder
	// WithId adds Id (property field)
	WithId(...byte) NodeIdGuidBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() NodeIdTypeDefinitionBuilder
	// Build builds the NodeIdGuid or returns an error if something is wrong
	Build() (NodeIdGuid, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NodeIdGuid
}

// NewNodeIdGuidBuilder() creates a NodeIdGuidBuilder
func NewNodeIdGuidBuilder() NodeIdGuidBuilder {
	return &_NodeIdGuidBuilder{_NodeIdGuid: new(_NodeIdGuid)}
}

type _NodeIdGuidBuilder struct {
	*_NodeIdGuid

	parentBuilder *_NodeIdTypeDefinitionBuilder

	collectedErr []error
}

var _ (NodeIdGuidBuilder) = (*_NodeIdGuidBuilder)(nil)

func (b *_NodeIdGuidBuilder) setParent(contract NodeIdTypeDefinitionContract) {
	b.NodeIdTypeDefinitionContract = contract
	contract.(*_NodeIdTypeDefinition)._SubType = b._NodeIdGuid
}

func (b *_NodeIdGuidBuilder) WithMandatoryFields(namespaceIndex uint16, id []byte) NodeIdGuidBuilder {
	return b.WithNamespaceIndex(namespaceIndex).WithId(id...)
}

func (b *_NodeIdGuidBuilder) WithNamespaceIndex(namespaceIndex uint16) NodeIdGuidBuilder {
	b.NamespaceIndex = namespaceIndex
	return b
}

func (b *_NodeIdGuidBuilder) WithId(id ...byte) NodeIdGuidBuilder {
	b.Id = id
	return b
}

func (b *_NodeIdGuidBuilder) Build() (NodeIdGuid, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._NodeIdGuid.deepCopy(), nil
}

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

func (b *_NodeIdGuidBuilder) Done() NodeIdTypeDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewNodeIdTypeDefinitionBuilder().(*_NodeIdTypeDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_NodeIdGuidBuilder) buildForNodeIdTypeDefinition() (NodeIdTypeDefinition, error) {
	return b.Build()
}

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

// CreateNodeIdGuidBuilder creates a NodeIdGuidBuilder
func (b *_NodeIdGuid) CreateNodeIdGuidBuilder() NodeIdGuidBuilder {
	if b == nil {
		return NewNodeIdGuidBuilder()
	}
	return &_NodeIdGuidBuilder{_NodeIdGuid: b.deepCopy()}
}

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

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

func (m *_NodeIdGuid) GetNodeType() NodeIdType {
	return NodeIdType_nodeIdTypeGuid
}

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

func (m *_NodeIdGuid) GetParent() NodeIdTypeDefinitionContract {
	return m.NodeIdTypeDefinitionContract
}

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

func (m *_NodeIdGuid) GetNamespaceIndex() uint16 {
	return m.NamespaceIndex
}

func (m *_NodeIdGuid) GetId() []byte {
	return m.Id
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for virtual fields.
///////////////////////

func (m *_NodeIdGuid) GetIdentifier() string {
	ctx := context.Background()
	_ = ctx
	return fmt.Sprintf("%v", m.GetId())
}

func (m *_NodeIdGuid) GetNamespace() int16 {
	ctx := context.Background()
	_ = ctx
	return int16(m.GetNamespaceIndex())
}

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

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

func (m *_NodeIdGuid) GetTypeName() string {
	return "NodeIdGuid"
}

func (m *_NodeIdGuid) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.NodeIdTypeDefinitionContract.(*_NodeIdTypeDefinition).getLengthInBits(ctx))

	// Simple field (namespaceIndex)
	lengthInBits += 16

	// Array field
	if len(m.Id) > 0 {
		lengthInBits += 8 * uint16(len(m.Id))
	}

	// A virtual field doesn't have any in- or output.

	// A virtual field doesn't have any in- or output.

	return lengthInBits
}

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

func (m *_NodeIdGuid) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_NodeIdTypeDefinition) (__nodeIdGuid NodeIdGuid, err error) {
	m.NodeIdTypeDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("NodeIdGuid"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for NodeIdGuid")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	namespaceIndex, err := ReadSimpleField(ctx, "namespaceIndex", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'namespaceIndex' field"))
	}
	m.NamespaceIndex = namespaceIndex

	id, err := readBuffer.ReadByteArray("id", int(int32(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'id' field"))
	}
	m.Id = id

	identifier, err := ReadVirtualField[string](ctx, "identifier", (*string)(nil), id)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'identifier' field"))
	}
	_ = identifier

	namespace, err := ReadVirtualField[int16](ctx, "namespace", (*int16)(nil), namespaceIndex)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'namespace' field"))
	}
	_ = namespace

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

	return m, nil
}

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

		if err := WriteSimpleField[uint16](ctx, "namespaceIndex", m.GetNamespaceIndex(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'namespaceIndex' field")
		}

		if err := WriteByteArrayField(ctx, "id", m.GetId(), WriteByteArray(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'id' field")
		}
		// Virtual field
		identifier := m.GetIdentifier()
		_ = identifier
		if _identifierErr := writeBuffer.WriteVirtual(ctx, "identifier", m.GetIdentifier()); _identifierErr != nil {
			return errors.Wrap(_identifierErr, "Error serializing 'identifier' field")
		}
		// Virtual field
		namespace := m.GetNamespace()
		_ = namespace
		if _namespaceErr := writeBuffer.WriteVirtual(ctx, "namespace", m.GetNamespace()); _namespaceErr != nil {
			return errors.Wrap(_namespaceErr, "Error serializing 'namespace' field")
		}

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

func (m *_NodeIdGuid) IsNodeIdGuid() {}

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

func (m *_NodeIdGuid) deepCopy() *_NodeIdGuid {
	if m == nil {
		return nil
	}
	_NodeIdGuidCopy := &_NodeIdGuid{
		m.NodeIdTypeDefinitionContract.(*_NodeIdTypeDefinition).deepCopy(),
		m.NamespaceIndex,
		utils.DeepCopySlice[byte, byte](m.Id),
	}
	_NodeIdGuidCopy.NodeIdTypeDefinitionContract.(*_NodeIdTypeDefinition)._SubType = m
	return _NodeIdGuidCopy
}

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