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

// Argument is the corresponding interface of Argument
type Argument interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetName returns Name (property field)
	GetName() PascalString
	// GetDataType returns DataType (property field)
	GetDataType() NodeId
	// GetValueRank returns ValueRank (property field)
	GetValueRank() int32
	// GetArrayDimensions returns ArrayDimensions (property field)
	GetArrayDimensions() []uint32
	// GetDescription returns Description (property field)
	GetDescription() LocalizedText
	// IsArgument is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsArgument()
	// CreateBuilder creates a ArgumentBuilder
	CreateArgumentBuilder() ArgumentBuilder
}

// _Argument is the data-structure of this message
type _Argument struct {
	ExtensionObjectDefinitionContract
	Name            PascalString
	DataType        NodeId
	ValueRank       int32
	ArrayDimensions []uint32
	Description     LocalizedText
}

var _ Argument = (*_Argument)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_Argument)(nil)

// NewArgument factory function for _Argument
func NewArgument(name PascalString, dataType NodeId, valueRank int32, arrayDimensions []uint32, description LocalizedText) *_Argument {
	if name == nil {
		panic("name of type PascalString for Argument must not be nil")
	}
	if dataType == nil {
		panic("dataType of type NodeId for Argument must not be nil")
	}
	if description == nil {
		panic("description of type LocalizedText for Argument must not be nil")
	}
	_result := &_Argument{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Name:                              name,
		DataType:                          dataType,
		ValueRank:                         valueRank,
		ArrayDimensions:                   arrayDimensions,
		Description:                       description,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ArgumentBuilder is a builder for Argument
type ArgumentBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name PascalString, dataType NodeId, valueRank int32, arrayDimensions []uint32, description LocalizedText) ArgumentBuilder
	// WithName adds Name (property field)
	WithName(PascalString) ArgumentBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) ArgumentBuilder
	// WithDataType adds DataType (property field)
	WithDataType(NodeId) ArgumentBuilder
	// WithDataTypeBuilder adds DataType (property field) which is build by the builder
	WithDataTypeBuilder(func(NodeIdBuilder) NodeIdBuilder) ArgumentBuilder
	// WithValueRank adds ValueRank (property field)
	WithValueRank(int32) ArgumentBuilder
	// WithArrayDimensions adds ArrayDimensions (property field)
	WithArrayDimensions(...uint32) ArgumentBuilder
	// WithDescription adds Description (property field)
	WithDescription(LocalizedText) ArgumentBuilder
	// WithDescriptionBuilder adds Description (property field) which is build by the builder
	WithDescriptionBuilder(func(LocalizedTextBuilder) LocalizedTextBuilder) ArgumentBuilder
	// 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 Argument or returns an error if something is wrong
	Build() (Argument, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() Argument
}

// NewArgumentBuilder() creates a ArgumentBuilder
func NewArgumentBuilder() ArgumentBuilder {
	return &_ArgumentBuilder{_Argument: new(_Argument)}
}

type _ArgumentBuilder struct {
	*_Argument

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ArgumentBuilder) = (*_ArgumentBuilder)(nil)

func (b *_ArgumentBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._Argument
}

func (b *_ArgumentBuilder) WithMandatoryFields(name PascalString, dataType NodeId, valueRank int32, arrayDimensions []uint32, description LocalizedText) ArgumentBuilder {
	return b.WithName(name).WithDataType(dataType).WithValueRank(valueRank).WithArrayDimensions(arrayDimensions...).WithDescription(description)
}

func (b *_ArgumentBuilder) WithName(name PascalString) ArgumentBuilder {
	b.Name = name
	return b
}

func (b *_ArgumentBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) ArgumentBuilder {
	builder := builderSupplier(b.Name.CreatePascalStringBuilder())
	var err error
	b.Name, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_ArgumentBuilder) WithDataType(dataType NodeId) ArgumentBuilder {
	b.DataType = dataType
	return b
}

func (b *_ArgumentBuilder) WithDataTypeBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) ArgumentBuilder {
	builder := builderSupplier(b.DataType.CreateNodeIdBuilder())
	var err error
	b.DataType, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_ArgumentBuilder) WithValueRank(valueRank int32) ArgumentBuilder {
	b.ValueRank = valueRank
	return b
}

func (b *_ArgumentBuilder) WithArrayDimensions(arrayDimensions ...uint32) ArgumentBuilder {
	b.ArrayDimensions = arrayDimensions
	return b
}

func (b *_ArgumentBuilder) WithDescription(description LocalizedText) ArgumentBuilder {
	b.Description = description
	return b
}

func (b *_ArgumentBuilder) WithDescriptionBuilder(builderSupplier func(LocalizedTextBuilder) LocalizedTextBuilder) ArgumentBuilder {
	builder := builderSupplier(b.Description.CreateLocalizedTextBuilder())
	var err error
	b.Description, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "LocalizedTextBuilder failed"))
	}
	return b
}

func (b *_ArgumentBuilder) Build() (Argument, error) {
	if b.Name == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'name' not set"))
	}
	if b.DataType == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'dataType' not set"))
	}
	if b.Description == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'description' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._Argument.deepCopy(), nil
}

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

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

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

func (b *_ArgumentBuilder) DeepCopy() any {
	_copy := b.CreateArgumentBuilder().(*_ArgumentBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateArgumentBuilder creates a ArgumentBuilder
func (b *_Argument) CreateArgumentBuilder() ArgumentBuilder {
	if b == nil {
		return NewArgumentBuilder()
	}
	return &_ArgumentBuilder{_Argument: b.deepCopy()}
}

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

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

func (m *_Argument) GetExtensionId() int32 {
	return int32(298)
}

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

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

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

func (m *_Argument) GetName() PascalString {
	return m.Name
}

func (m *_Argument) GetDataType() NodeId {
	return m.DataType
}

func (m *_Argument) GetValueRank() int32 {
	return m.ValueRank
}

func (m *_Argument) GetArrayDimensions() []uint32 {
	return m.ArrayDimensions
}

func (m *_Argument) GetDescription() LocalizedText {
	return m.Description
}

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

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

func (m *_Argument) GetTypeName() string {
	return "Argument"
}

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

	// Simple field (name)
	lengthInBits += m.Name.GetLengthInBits(ctx)

	// Simple field (dataType)
	lengthInBits += m.DataType.GetLengthInBits(ctx)

	// Simple field (valueRank)
	lengthInBits += 32

	// Implicit Field (noOfArrayDimensions)
	lengthInBits += 32

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

	// Simple field (description)
	lengthInBits += m.Description.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

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

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

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

	noOfArrayDimensions, err := ReadImplicitField[int32](ctx, "noOfArrayDimensions", ReadSignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'noOfArrayDimensions' field"))
	}
	_ = noOfArrayDimensions

	arrayDimensions, err := ReadCountArrayField[uint32](ctx, "arrayDimensions", ReadUnsignedInt(readBuffer, uint8(32)), uint64(noOfArrayDimensions))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'arrayDimensions' field"))
	}
	m.ArrayDimensions = arrayDimensions

	description, err := ReadSimpleField[LocalizedText](ctx, "description", ReadComplex[LocalizedText](LocalizedTextParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'description' field"))
	}
	m.Description = description

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

	return m, nil
}

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

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

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

		if err := WriteSimpleField[int32](ctx, "valueRank", m.GetValueRank(), WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'valueRank' field")
		}
		noOfArrayDimensions := int32(utils.InlineIf(bool((m.GetArrayDimensions()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetArrayDimensions()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfArrayDimensions", noOfArrayDimensions, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfArrayDimensions' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "arrayDimensions", m.GetArrayDimensions(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'arrayDimensions' field")
		}

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

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

func (m *_Argument) IsArgument() {}

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

func (m *_Argument) deepCopy() *_Argument {
	if m == nil {
		return nil
	}
	_ArgumentCopy := &_Argument{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.Name),
		utils.DeepCopy[NodeId](m.DataType),
		m.ValueRank,
		utils.DeepCopySlice[uint32, uint32](m.ArrayDimensions),
		utils.DeepCopy[LocalizedText](m.Description),
	}
	_ArgumentCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ArgumentCopy
}

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