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

// BACnetPropertyWriteDefinition is the corresponding interface of BACnetPropertyWriteDefinition
type BACnetPropertyWriteDefinition interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetPropertyIdentifier returns PropertyIdentifier (property field)
	GetPropertyIdentifier() BACnetPropertyIdentifierTagged
	// GetArrayIndex returns ArrayIndex (property field)
	GetArrayIndex() BACnetContextTagUnsignedInteger
	// GetPropertyValue returns PropertyValue (property field)
	GetPropertyValue() BACnetConstructedData
	// GetPriority returns Priority (property field)
	GetPriority() BACnetContextTagUnsignedInteger
	// IsBACnetPropertyWriteDefinition is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBACnetPropertyWriteDefinition()
	// CreateBuilder creates a BACnetPropertyWriteDefinitionBuilder
	CreateBACnetPropertyWriteDefinitionBuilder() BACnetPropertyWriteDefinitionBuilder
}

// _BACnetPropertyWriteDefinition is the data-structure of this message
type _BACnetPropertyWriteDefinition struct {
	PropertyIdentifier BACnetPropertyIdentifierTagged
	ArrayIndex         BACnetContextTagUnsignedInteger
	PropertyValue      BACnetConstructedData
	Priority           BACnetContextTagUnsignedInteger
}

var _ BACnetPropertyWriteDefinition = (*_BACnetPropertyWriteDefinition)(nil)

// NewBACnetPropertyWriteDefinition factory function for _BACnetPropertyWriteDefinition
func NewBACnetPropertyWriteDefinition(propertyIdentifier BACnetPropertyIdentifierTagged, arrayIndex BACnetContextTagUnsignedInteger, propertyValue BACnetConstructedData, priority BACnetContextTagUnsignedInteger) *_BACnetPropertyWriteDefinition {
	if propertyIdentifier == nil {
		panic("propertyIdentifier of type BACnetPropertyIdentifierTagged for BACnetPropertyWriteDefinition must not be nil")
	}
	return &_BACnetPropertyWriteDefinition{PropertyIdentifier: propertyIdentifier, ArrayIndex: arrayIndex, PropertyValue: propertyValue, Priority: priority}
}

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

// BACnetPropertyWriteDefinitionBuilder is a builder for BACnetPropertyWriteDefinition
type BACnetPropertyWriteDefinitionBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(propertyIdentifier BACnetPropertyIdentifierTagged) BACnetPropertyWriteDefinitionBuilder
	// WithPropertyIdentifier adds PropertyIdentifier (property field)
	WithPropertyIdentifier(BACnetPropertyIdentifierTagged) BACnetPropertyWriteDefinitionBuilder
	// WithPropertyIdentifierBuilder adds PropertyIdentifier (property field) which is build by the builder
	WithPropertyIdentifierBuilder(func(BACnetPropertyIdentifierTaggedBuilder) BACnetPropertyIdentifierTaggedBuilder) BACnetPropertyWriteDefinitionBuilder
	// WithArrayIndex adds ArrayIndex (property field)
	WithOptionalArrayIndex(BACnetContextTagUnsignedInteger) BACnetPropertyWriteDefinitionBuilder
	// WithOptionalArrayIndexBuilder adds ArrayIndex (property field) which is build by the builder
	WithOptionalArrayIndexBuilder(func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPropertyWriteDefinitionBuilder
	// WithPropertyValue adds PropertyValue (property field)
	WithOptionalPropertyValue(BACnetConstructedData) BACnetPropertyWriteDefinitionBuilder
	// WithOptionalPropertyValueBuilder adds PropertyValue (property field) which is build by the builder
	WithOptionalPropertyValueBuilder(func(BACnetConstructedDataBuilder) BACnetConstructedDataBuilder) BACnetPropertyWriteDefinitionBuilder
	// WithPriority adds Priority (property field)
	WithOptionalPriority(BACnetContextTagUnsignedInteger) BACnetPropertyWriteDefinitionBuilder
	// WithOptionalPriorityBuilder adds Priority (property field) which is build by the builder
	WithOptionalPriorityBuilder(func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPropertyWriteDefinitionBuilder
	// Build builds the BACnetPropertyWriteDefinition or returns an error if something is wrong
	Build() (BACnetPropertyWriteDefinition, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BACnetPropertyWriteDefinition
}

// NewBACnetPropertyWriteDefinitionBuilder() creates a BACnetPropertyWriteDefinitionBuilder
func NewBACnetPropertyWriteDefinitionBuilder() BACnetPropertyWriteDefinitionBuilder {
	return &_BACnetPropertyWriteDefinitionBuilder{_BACnetPropertyWriteDefinition: new(_BACnetPropertyWriteDefinition)}
}

type _BACnetPropertyWriteDefinitionBuilder struct {
	*_BACnetPropertyWriteDefinition

	collectedErr []error
}

var _ (BACnetPropertyWriteDefinitionBuilder) = (*_BACnetPropertyWriteDefinitionBuilder)(nil)

func (b *_BACnetPropertyWriteDefinitionBuilder) WithMandatoryFields(propertyIdentifier BACnetPropertyIdentifierTagged) BACnetPropertyWriteDefinitionBuilder {
	return b.WithPropertyIdentifier(propertyIdentifier)
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithPropertyIdentifier(propertyIdentifier BACnetPropertyIdentifierTagged) BACnetPropertyWriteDefinitionBuilder {
	b.PropertyIdentifier = propertyIdentifier
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithPropertyIdentifierBuilder(builderSupplier func(BACnetPropertyIdentifierTaggedBuilder) BACnetPropertyIdentifierTaggedBuilder) BACnetPropertyWriteDefinitionBuilder {
	builder := builderSupplier(b.PropertyIdentifier.CreateBACnetPropertyIdentifierTaggedBuilder())
	var err error
	b.PropertyIdentifier, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetPropertyIdentifierTaggedBuilder failed"))
	}
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalArrayIndex(arrayIndex BACnetContextTagUnsignedInteger) BACnetPropertyWriteDefinitionBuilder {
	b.ArrayIndex = arrayIndex
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalArrayIndexBuilder(builderSupplier func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPropertyWriteDefinitionBuilder {
	builder := builderSupplier(b.ArrayIndex.CreateBACnetContextTagUnsignedIntegerBuilder())
	var err error
	b.ArrayIndex, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetContextTagUnsignedIntegerBuilder failed"))
	}
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalPropertyValue(propertyValue BACnetConstructedData) BACnetPropertyWriteDefinitionBuilder {
	b.PropertyValue = propertyValue
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalPropertyValueBuilder(builderSupplier func(BACnetConstructedDataBuilder) BACnetConstructedDataBuilder) BACnetPropertyWriteDefinitionBuilder {
	builder := builderSupplier(b.PropertyValue.CreateBACnetConstructedDataBuilder())
	var err error
	b.PropertyValue, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetConstructedDataBuilder failed"))
	}
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalPriority(priority BACnetContextTagUnsignedInteger) BACnetPropertyWriteDefinitionBuilder {
	b.Priority = priority
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) WithOptionalPriorityBuilder(builderSupplier func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPropertyWriteDefinitionBuilder {
	builder := builderSupplier(b.Priority.CreateBACnetContextTagUnsignedIntegerBuilder())
	var err error
	b.Priority, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetContextTagUnsignedIntegerBuilder failed"))
	}
	return b
}

func (b *_BACnetPropertyWriteDefinitionBuilder) Build() (BACnetPropertyWriteDefinition, error) {
	if b.PropertyIdentifier == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'propertyIdentifier' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._BACnetPropertyWriteDefinition.deepCopy(), nil
}

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

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

// CreateBACnetPropertyWriteDefinitionBuilder creates a BACnetPropertyWriteDefinitionBuilder
func (b *_BACnetPropertyWriteDefinition) CreateBACnetPropertyWriteDefinitionBuilder() BACnetPropertyWriteDefinitionBuilder {
	if b == nil {
		return NewBACnetPropertyWriteDefinitionBuilder()
	}
	return &_BACnetPropertyWriteDefinitionBuilder{_BACnetPropertyWriteDefinition: b.deepCopy()}
}

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

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

func (m *_BACnetPropertyWriteDefinition) GetPropertyIdentifier() BACnetPropertyIdentifierTagged {
	return m.PropertyIdentifier
}

func (m *_BACnetPropertyWriteDefinition) GetArrayIndex() BACnetContextTagUnsignedInteger {
	return m.ArrayIndex
}

func (m *_BACnetPropertyWriteDefinition) GetPropertyValue() BACnetConstructedData {
	return m.PropertyValue
}

func (m *_BACnetPropertyWriteDefinition) GetPriority() BACnetContextTagUnsignedInteger {
	return m.Priority
}

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

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

func (m *_BACnetPropertyWriteDefinition) GetTypeName() string {
	return "BACnetPropertyWriteDefinition"
}

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

	// Simple field (propertyIdentifier)
	lengthInBits += m.PropertyIdentifier.GetLengthInBits(ctx)

	// Optional Field (arrayIndex)
	if m.ArrayIndex != nil {
		lengthInBits += m.ArrayIndex.GetLengthInBits(ctx)
	}

	// Optional Field (propertyValue)
	if m.PropertyValue != nil {
		lengthInBits += m.PropertyValue.GetLengthInBits(ctx)
	}

	// Optional Field (priority)
	if m.Priority != nil {
		lengthInBits += m.Priority.GetLengthInBits(ctx)
	}

	return lengthInBits
}

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

func BACnetPropertyWriteDefinitionParse(ctx context.Context, theBytes []byte, objectTypeArgument BACnetObjectType) (BACnetPropertyWriteDefinition, error) {
	return BACnetPropertyWriteDefinitionParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes), objectTypeArgument)
}

func BACnetPropertyWriteDefinitionParseWithBufferProducer(objectTypeArgument BACnetObjectType) func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetPropertyWriteDefinition, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetPropertyWriteDefinition, error) {
		return BACnetPropertyWriteDefinitionParseWithBuffer(ctx, readBuffer, objectTypeArgument)
	}
}

func BACnetPropertyWriteDefinitionParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer, objectTypeArgument BACnetObjectType) (BACnetPropertyWriteDefinition, error) {
	v, err := (new(_BACnetPropertyWriteDefinition)).parse(ctx, readBuffer, objectTypeArgument)
	if err != nil {
		return nil, err
	}
	return v, nil
}

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

	propertyIdentifier, err := ReadSimpleField[BACnetPropertyIdentifierTagged](ctx, "propertyIdentifier", ReadComplex[BACnetPropertyIdentifierTagged](BACnetPropertyIdentifierTaggedParseWithBufferProducer((uint8)(uint8(0)), (TagClass)(TagClass_CONTEXT_SPECIFIC_TAGS)), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'propertyIdentifier' field"))
	}
	m.PropertyIdentifier = propertyIdentifier

	var arrayIndex BACnetContextTagUnsignedInteger
	_arrayIndex, err := ReadOptionalField[BACnetContextTagUnsignedInteger](ctx, "arrayIndex", ReadComplex[BACnetContextTagUnsignedInteger](BACnetContextTagParseWithBufferProducer[BACnetContextTagUnsignedInteger]((uint8)(uint8(1)), (BACnetDataType)(BACnetDataType_UNSIGNED_INTEGER)), readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'arrayIndex' field"))
	}
	if _arrayIndex != nil {
		arrayIndex = *_arrayIndex
		m.ArrayIndex = arrayIndex
	}

	var propertyValue BACnetConstructedData
	_propertyValue, err := ReadOptionalField[BACnetConstructedData](ctx, "propertyValue", ReadComplex[BACnetConstructedData](BACnetConstructedDataParseWithBufferProducer[BACnetConstructedData]((uint8)(uint8(2)), (BACnetObjectType)(objectTypeArgument), (BACnetPropertyIdentifier)(propertyIdentifier.GetValue()), (BACnetTagPayloadUnsignedInteger)((CastBACnetTagPayloadUnsignedInteger(utils.InlineIf(bool((arrayIndex) != (nil)), func() any { return CastBACnetTagPayloadUnsignedInteger((arrayIndex).GetPayload()) }, func() any { return CastBACnetTagPayloadUnsignedInteger(nil) }))))), readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'propertyValue' field"))
	}
	if _propertyValue != nil {
		propertyValue = *_propertyValue
		m.PropertyValue = propertyValue
	}

	var priority BACnetContextTagUnsignedInteger
	_priority, err := ReadOptionalField[BACnetContextTagUnsignedInteger](ctx, "priority", ReadComplex[BACnetContextTagUnsignedInteger](BACnetContextTagParseWithBufferProducer[BACnetContextTagUnsignedInteger]((uint8)(uint8(3)), (BACnetDataType)(BACnetDataType_UNSIGNED_INTEGER)), readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'priority' field"))
	}
	if _priority != nil {
		priority = *_priority
		m.Priority = priority
	}

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

	return m, nil
}

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

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

	if err := WriteOptionalField[BACnetContextTagUnsignedInteger](ctx, "arrayIndex", GetRef(m.GetArrayIndex()), WriteComplex[BACnetContextTagUnsignedInteger](writeBuffer), true); err != nil {
		return errors.Wrap(err, "Error serializing 'arrayIndex' field")
	}

	if err := WriteOptionalField[BACnetConstructedData](ctx, "propertyValue", GetRef(m.GetPropertyValue()), WriteComplex[BACnetConstructedData](writeBuffer), true); err != nil {
		return errors.Wrap(err, "Error serializing 'propertyValue' field")
	}

	if err := WriteOptionalField[BACnetContextTagUnsignedInteger](ctx, "priority", GetRef(m.GetPriority()), WriteComplex[BACnetContextTagUnsignedInteger](writeBuffer), true); err != nil {
		return errors.Wrap(err, "Error serializing 'priority' field")
	}

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

func (m *_BACnetPropertyWriteDefinition) IsBACnetPropertyWriteDefinition() {}

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

func (m *_BACnetPropertyWriteDefinition) deepCopy() *_BACnetPropertyWriteDefinition {
	if m == nil {
		return nil
	}
	_BACnetPropertyWriteDefinitionCopy := &_BACnetPropertyWriteDefinition{
		utils.DeepCopy[BACnetPropertyIdentifierTagged](m.PropertyIdentifier),
		utils.DeepCopy[BACnetContextTagUnsignedInteger](m.ArrayIndex),
		utils.DeepCopy[BACnetConstructedData](m.PropertyValue),
		utils.DeepCopy[BACnetContextTagUnsignedInteger](m.Priority),
	}
	return _BACnetPropertyWriteDefinitionCopy
}

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