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

// WriteValue is the corresponding interface of WriteValue
type WriteValue interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetAttributeId returns AttributeId (property field)
	GetAttributeId() uint32
	// GetIndexRange returns IndexRange (property field)
	GetIndexRange() PascalString
	// GetValue returns Value (property field)
	GetValue() DataValue
	// IsWriteValue is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsWriteValue()
	// CreateBuilder creates a WriteValueBuilder
	CreateWriteValueBuilder() WriteValueBuilder
}

// _WriteValue is the data-structure of this message
type _WriteValue struct {
	ExtensionObjectDefinitionContract
	NodeId      NodeId
	AttributeId uint32
	IndexRange  PascalString
	Value       DataValue
}

var _ WriteValue = (*_WriteValue)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_WriteValue)(nil)

// NewWriteValue factory function for _WriteValue
func NewWriteValue(nodeId NodeId, attributeId uint32, indexRange PascalString, value DataValue) *_WriteValue {
	if nodeId == nil {
		panic("nodeId of type NodeId for WriteValue must not be nil")
	}
	if indexRange == nil {
		panic("indexRange of type PascalString for WriteValue must not be nil")
	}
	if value == nil {
		panic("value of type DataValue for WriteValue must not be nil")
	}
	_result := &_WriteValue{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		AttributeId:                       attributeId,
		IndexRange:                        indexRange,
		Value:                             value,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// WriteValueBuilder is a builder for WriteValue
type WriteValueBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, attributeId uint32, indexRange PascalString, value DataValue) WriteValueBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) WriteValueBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) WriteValueBuilder
	// WithAttributeId adds AttributeId (property field)
	WithAttributeId(uint32) WriteValueBuilder
	// WithIndexRange adds IndexRange (property field)
	WithIndexRange(PascalString) WriteValueBuilder
	// WithIndexRangeBuilder adds IndexRange (property field) which is build by the builder
	WithIndexRangeBuilder(func(PascalStringBuilder) PascalStringBuilder) WriteValueBuilder
	// WithValue adds Value (property field)
	WithValue(DataValue) WriteValueBuilder
	// WithValueBuilder adds Value (property field) which is build by the builder
	WithValueBuilder(func(DataValueBuilder) DataValueBuilder) WriteValueBuilder
	// 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 WriteValue or returns an error if something is wrong
	Build() (WriteValue, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() WriteValue
}

// NewWriteValueBuilder() creates a WriteValueBuilder
func NewWriteValueBuilder() WriteValueBuilder {
	return &_WriteValueBuilder{_WriteValue: new(_WriteValue)}
}

type _WriteValueBuilder struct {
	*_WriteValue

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (WriteValueBuilder) = (*_WriteValueBuilder)(nil)

func (b *_WriteValueBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._WriteValue
}

func (b *_WriteValueBuilder) WithMandatoryFields(nodeId NodeId, attributeId uint32, indexRange PascalString, value DataValue) WriteValueBuilder {
	return b.WithNodeId(nodeId).WithAttributeId(attributeId).WithIndexRange(indexRange).WithValue(value)
}

func (b *_WriteValueBuilder) WithNodeId(nodeId NodeId) WriteValueBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_WriteValueBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) WriteValueBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdBuilder())
	var err error
	b.NodeId, 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 *_WriteValueBuilder) WithAttributeId(attributeId uint32) WriteValueBuilder {
	b.AttributeId = attributeId
	return b
}

func (b *_WriteValueBuilder) WithIndexRange(indexRange PascalString) WriteValueBuilder {
	b.IndexRange = indexRange
	return b
}

func (b *_WriteValueBuilder) WithIndexRangeBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) WriteValueBuilder {
	builder := builderSupplier(b.IndexRange.CreatePascalStringBuilder())
	var err error
	b.IndexRange, 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 *_WriteValueBuilder) WithValue(value DataValue) WriteValueBuilder {
	b.Value = value
	return b
}

func (b *_WriteValueBuilder) WithValueBuilder(builderSupplier func(DataValueBuilder) DataValueBuilder) WriteValueBuilder {
	builder := builderSupplier(b.Value.CreateDataValueBuilder())
	var err error
	b.Value, 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, "DataValueBuilder failed"))
	}
	return b
}

func (b *_WriteValueBuilder) Build() (WriteValue, error) {
	if b.NodeId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'nodeId' not set"))
	}
	if b.IndexRange == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'indexRange' not set"))
	}
	if b.Value == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'value' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._WriteValue.deepCopy(), nil
}

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

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

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

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

// CreateWriteValueBuilder creates a WriteValueBuilder
func (b *_WriteValue) CreateWriteValueBuilder() WriteValueBuilder {
	if b == nil {
		return NewWriteValueBuilder()
	}
	return &_WriteValueBuilder{_WriteValue: b.deepCopy()}
}

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

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

func (m *_WriteValue) GetExtensionId() int32 {
	return int32(670)
}

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

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

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

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

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

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

func (m *_WriteValue) GetValue() DataValue {
	return m.Value
}

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

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

func (m *_WriteValue) GetTypeName() string {
	return "WriteValue"
}

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

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

	// Simple field (attributeId)
	lengthInBits += 32

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

	// Simple field (value)
	lengthInBits += m.Value.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	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

	value, err := ReadSimpleField[DataValue](ctx, "value", ReadComplex[DataValue](DataValueParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'value' field"))
	}
	m.Value = value

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

	return m, nil
}

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

		if err := WriteSimpleField[NodeId](ctx, "nodeId", m.GetNodeId(), WriteComplex[NodeId](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'nodeId' 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 err := WriteSimpleField[DataValue](ctx, "value", m.GetValue(), WriteComplex[DataValue](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'value' field")
		}

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

func (m *_WriteValue) IsWriteValue() {}

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

func (m *_WriteValue) deepCopy() *_WriteValue {
	if m == nil {
		return nil
	}
	_WriteValueCopy := &_WriteValue{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		m.AttributeId,
		utils.DeepCopy[PascalString](m.IndexRange),
		utils.DeepCopy[DataValue](m.Value),
	}
	_WriteValueCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _WriteValueCopy
}

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