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

// AttributeOperand is the corresponding interface of AttributeOperand
type AttributeOperand interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetAlias returns Alias (property field)
	GetAlias() PascalString
	// GetBrowsePath returns BrowsePath (property field)
	GetBrowsePath() RelativePath
	// GetAttributeId returns AttributeId (property field)
	GetAttributeId() uint32
	// GetIndexRange returns IndexRange (property field)
	GetIndexRange() PascalString
	// IsAttributeOperand is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsAttributeOperand()
	// CreateBuilder creates a AttributeOperandBuilder
	CreateAttributeOperandBuilder() AttributeOperandBuilder
}

// _AttributeOperand is the data-structure of this message
type _AttributeOperand struct {
	ExtensionObjectDefinitionContract
	NodeId      NodeId
	Alias       PascalString
	BrowsePath  RelativePath
	AttributeId uint32
	IndexRange  PascalString
}

var _ AttributeOperand = (*_AttributeOperand)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_AttributeOperand)(nil)

// NewAttributeOperand factory function for _AttributeOperand
func NewAttributeOperand(nodeId NodeId, alias PascalString, browsePath RelativePath, attributeId uint32, indexRange PascalString) *_AttributeOperand {
	if nodeId == nil {
		panic("nodeId of type NodeId for AttributeOperand must not be nil")
	}
	if alias == nil {
		panic("alias of type PascalString for AttributeOperand must not be nil")
	}
	if browsePath == nil {
		panic("browsePath of type RelativePath for AttributeOperand must not be nil")
	}
	if indexRange == nil {
		panic("indexRange of type PascalString for AttributeOperand must not be nil")
	}
	_result := &_AttributeOperand{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		Alias:                             alias,
		BrowsePath:                        browsePath,
		AttributeId:                       attributeId,
		IndexRange:                        indexRange,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// AttributeOperandBuilder is a builder for AttributeOperand
type AttributeOperandBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, alias PascalString, browsePath RelativePath, attributeId uint32, indexRange PascalString) AttributeOperandBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) AttributeOperandBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) AttributeOperandBuilder
	// WithAlias adds Alias (property field)
	WithAlias(PascalString) AttributeOperandBuilder
	// WithAliasBuilder adds Alias (property field) which is build by the builder
	WithAliasBuilder(func(PascalStringBuilder) PascalStringBuilder) AttributeOperandBuilder
	// WithBrowsePath adds BrowsePath (property field)
	WithBrowsePath(RelativePath) AttributeOperandBuilder
	// WithBrowsePathBuilder adds BrowsePath (property field) which is build by the builder
	WithBrowsePathBuilder(func(RelativePathBuilder) RelativePathBuilder) AttributeOperandBuilder
	// WithAttributeId adds AttributeId (property field)
	WithAttributeId(uint32) AttributeOperandBuilder
	// WithIndexRange adds IndexRange (property field)
	WithIndexRange(PascalString) AttributeOperandBuilder
	// WithIndexRangeBuilder adds IndexRange (property field) which is build by the builder
	WithIndexRangeBuilder(func(PascalStringBuilder) PascalStringBuilder) AttributeOperandBuilder
	// 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 AttributeOperand or returns an error if something is wrong
	Build() (AttributeOperand, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() AttributeOperand
}

// NewAttributeOperandBuilder() creates a AttributeOperandBuilder
func NewAttributeOperandBuilder() AttributeOperandBuilder {
	return &_AttributeOperandBuilder{_AttributeOperand: new(_AttributeOperand)}
}

type _AttributeOperandBuilder struct {
	*_AttributeOperand

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (AttributeOperandBuilder) = (*_AttributeOperandBuilder)(nil)

func (b *_AttributeOperandBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._AttributeOperand
}

func (b *_AttributeOperandBuilder) WithMandatoryFields(nodeId NodeId, alias PascalString, browsePath RelativePath, attributeId uint32, indexRange PascalString) AttributeOperandBuilder {
	return b.WithNodeId(nodeId).WithAlias(alias).WithBrowsePath(browsePath).WithAttributeId(attributeId).WithIndexRange(indexRange)
}

func (b *_AttributeOperandBuilder) WithNodeId(nodeId NodeId) AttributeOperandBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_AttributeOperandBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) AttributeOperandBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdBuilder())
	var err error
	b.NodeId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_AttributeOperandBuilder) WithAlias(alias PascalString) AttributeOperandBuilder {
	b.Alias = alias
	return b
}

func (b *_AttributeOperandBuilder) WithAliasBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) AttributeOperandBuilder {
	builder := builderSupplier(b.Alias.CreatePascalStringBuilder())
	var err error
	b.Alias, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_AttributeOperandBuilder) WithBrowsePath(browsePath RelativePath) AttributeOperandBuilder {
	b.BrowsePath = browsePath
	return b
}

func (b *_AttributeOperandBuilder) WithBrowsePathBuilder(builderSupplier func(RelativePathBuilder) RelativePathBuilder) AttributeOperandBuilder {
	builder := builderSupplier(b.BrowsePath.CreateRelativePathBuilder())
	var err error
	b.BrowsePath, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "RelativePathBuilder failed"))
	}
	return b
}

func (b *_AttributeOperandBuilder) WithAttributeId(attributeId uint32) AttributeOperandBuilder {
	b.AttributeId = attributeId
	return b
}

func (b *_AttributeOperandBuilder) WithIndexRange(indexRange PascalString) AttributeOperandBuilder {
	b.IndexRange = indexRange
	return b
}

func (b *_AttributeOperandBuilder) WithIndexRangeBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) AttributeOperandBuilder {
	builder := builderSupplier(b.IndexRange.CreatePascalStringBuilder())
	var err error
	b.IndexRange, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_AttributeOperandBuilder) Build() (AttributeOperand, error) {
	if b.NodeId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'nodeId' not set"))
	}
	if b.Alias == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'alias' not set"))
	}
	if b.BrowsePath == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'browsePath' not set"))
	}
	if b.IndexRange == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'indexRange' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._AttributeOperand.deepCopy(), nil
}

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

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

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

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

// CreateAttributeOperandBuilder creates a AttributeOperandBuilder
func (b *_AttributeOperand) CreateAttributeOperandBuilder() AttributeOperandBuilder {
	if b == nil {
		return NewAttributeOperandBuilder()
	}
	return &_AttributeOperandBuilder{_AttributeOperand: b.deepCopy()}
}

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

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

func (m *_AttributeOperand) GetExtensionId() int32 {
	return int32(600)
}

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

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

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

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

func (m *_AttributeOperand) GetAlias() PascalString {
	return m.Alias
}

func (m *_AttributeOperand) GetBrowsePath() RelativePath {
	return m.BrowsePath
}

func (m *_AttributeOperand) GetAttributeId() uint32 {
	return m.AttributeId
}

func (m *_AttributeOperand) GetIndexRange() PascalString {
	return m.IndexRange
}

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

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

func (m *_AttributeOperand) GetTypeName() string {
	return "AttributeOperand"
}

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

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

	// Simple field (alias)
	lengthInBits += m.Alias.GetLengthInBits(ctx)

	// Simple field (browsePath)
	lengthInBits += m.BrowsePath.GetLengthInBits(ctx)

	// Simple field (attributeId)
	lengthInBits += 32

	// Simple field (indexRange)
	lengthInBits += m.IndexRange.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

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

	browsePath, err := ReadSimpleField[RelativePath](ctx, "browsePath", ReadComplex[RelativePath](ExtensionObjectDefinitionParseWithBufferProducer[RelativePath]((int32)(int32(542))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'browsePath' field"))
	}
	m.BrowsePath = browsePath

	attributeId, err := ReadSimpleField(ctx, "attributeId", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'attributeId' field"))
	}
	m.AttributeId = attributeId

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

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

	return m, nil
}

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

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

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

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

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

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

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

func (m *_AttributeOperand) IsAttributeOperand() {}

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

func (m *_AttributeOperand) deepCopy() *_AttributeOperand {
	if m == nil {
		return nil
	}
	_AttributeOperandCopy := &_AttributeOperand{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		utils.DeepCopy[PascalString](m.Alias),
		utils.DeepCopy[RelativePath](m.BrowsePath),
		m.AttributeId,
		utils.DeepCopy[PascalString](m.IndexRange),
	}
	_AttributeOperandCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _AttributeOperandCopy
}

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