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

// NodeId is the corresponding interface of NodeId
type NodeId interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeIdTypeDefinition
	// IsNodeId is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNodeId()
	// CreateBuilder creates a NodeIdBuilder
	CreateNodeIdBuilder() NodeIdBuilder
}

// _NodeId is the data-structure of this message
type _NodeId struct {
	NodeId NodeIdTypeDefinition
	// Reserved Fields
	reservedField0 *int8
}

var _ NodeId = (*_NodeId)(nil)

// NewNodeId factory function for _NodeId
func NewNodeId(nodeId NodeIdTypeDefinition) *_NodeId {
	if nodeId == nil {
		panic("nodeId of type NodeIdTypeDefinition for NodeId must not be nil")
	}
	return &_NodeId{NodeId: nodeId}
}

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

// NodeIdBuilder is a builder for NodeId
type NodeIdBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeIdTypeDefinition) NodeIdBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeIdTypeDefinition) NodeIdBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdTypeDefinitionBuilder) NodeIdTypeDefinitionBuilder) NodeIdBuilder
	// Build builds the NodeId or returns an error if something is wrong
	Build() (NodeId, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NodeId
}

// NewNodeIdBuilder() creates a NodeIdBuilder
func NewNodeIdBuilder() NodeIdBuilder {
	return &_NodeIdBuilder{_NodeId: new(_NodeId)}
}

type _NodeIdBuilder struct {
	*_NodeId

	collectedErr []error
}

var _ (NodeIdBuilder) = (*_NodeIdBuilder)(nil)

func (b *_NodeIdBuilder) WithMandatoryFields(nodeId NodeIdTypeDefinition) NodeIdBuilder {
	return b.WithNodeId(nodeId)
}

func (b *_NodeIdBuilder) WithNodeId(nodeId NodeIdTypeDefinition) NodeIdBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_NodeIdBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdTypeDefinitionBuilder) NodeIdTypeDefinitionBuilder) NodeIdBuilder {
	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 *_NodeIdBuilder) Build() (NodeId, 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._NodeId.deepCopy(), nil
}

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

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

// CreateNodeIdBuilder creates a NodeIdBuilder
func (b *_NodeId) CreateNodeIdBuilder() NodeIdBuilder {
	if b == nil {
		return NewNodeIdBuilder()
	}
	return &_NodeIdBuilder{_NodeId: b.deepCopy()}
}

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

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

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

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

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

func (m *_NodeId) GetTypeName() string {
	return "NodeId"
}

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

	// Reserved Field (reserved)
	lengthInBits += 2

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

	return lengthInBits
}

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

func NodeIdParse(ctx context.Context, theBytes []byte) (NodeId, error) {
	return NodeIdParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func NodeIdParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (NodeId, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (NodeId, error) {
		return NodeIdParseWithBuffer(ctx, readBuffer)
	}
}

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

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

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

	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

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

	return m, nil
}

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

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

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

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

func (m *_NodeId) IsNodeId() {}

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

func (m *_NodeId) deepCopy() *_NodeId {
	if m == nil {
		return nil
	}
	_NodeIdCopy := &_NodeId{
		utils.DeepCopy[NodeIdTypeDefinition](m.NodeId),
		m.reservedField0,
	}
	return _NodeIdCopy
}

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