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

// BACnetNameValue is the corresponding interface of BACnetNameValue
type BACnetNameValue interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetName returns Name (property field)
	GetName() BACnetContextTagCharacterString
	// GetValue returns Value (property field)
	GetValue() BACnetConstructedData
	// IsBACnetNameValue is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBACnetNameValue()
	// CreateBuilder creates a BACnetNameValueBuilder
	CreateBACnetNameValueBuilder() BACnetNameValueBuilder
}

// _BACnetNameValue is the data-structure of this message
type _BACnetNameValue struct {
	Name  BACnetContextTagCharacterString
	Value BACnetConstructedData
}

var _ BACnetNameValue = (*_BACnetNameValue)(nil)

// NewBACnetNameValue factory function for _BACnetNameValue
func NewBACnetNameValue(name BACnetContextTagCharacterString, value BACnetConstructedData) *_BACnetNameValue {
	if name == nil {
		panic("name of type BACnetContextTagCharacterString for BACnetNameValue must not be nil")
	}
	return &_BACnetNameValue{Name: name, Value: value}
}

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

// BACnetNameValueBuilder is a builder for BACnetNameValue
type BACnetNameValueBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name BACnetContextTagCharacterString) BACnetNameValueBuilder
	// WithName adds Name (property field)
	WithName(BACnetContextTagCharacterString) BACnetNameValueBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(BACnetContextTagCharacterStringBuilder) BACnetContextTagCharacterStringBuilder) BACnetNameValueBuilder
	// WithValue adds Value (property field)
	WithOptionalValue(BACnetConstructedData) BACnetNameValueBuilder
	// WithOptionalValueBuilder adds Value (property field) which is build by the builder
	WithOptionalValueBuilder(func(BACnetConstructedDataBuilder) BACnetConstructedDataBuilder) BACnetNameValueBuilder
	// Build builds the BACnetNameValue or returns an error if something is wrong
	Build() (BACnetNameValue, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BACnetNameValue
}

// NewBACnetNameValueBuilder() creates a BACnetNameValueBuilder
func NewBACnetNameValueBuilder() BACnetNameValueBuilder {
	return &_BACnetNameValueBuilder{_BACnetNameValue: new(_BACnetNameValue)}
}

type _BACnetNameValueBuilder struct {
	*_BACnetNameValue

	collectedErr []error
}

var _ (BACnetNameValueBuilder) = (*_BACnetNameValueBuilder)(nil)

func (b *_BACnetNameValueBuilder) WithMandatoryFields(name BACnetContextTagCharacterString) BACnetNameValueBuilder {
	return b.WithName(name)
}

func (b *_BACnetNameValueBuilder) WithName(name BACnetContextTagCharacterString) BACnetNameValueBuilder {
	b.Name = name
	return b
}

func (b *_BACnetNameValueBuilder) WithNameBuilder(builderSupplier func(BACnetContextTagCharacterStringBuilder) BACnetContextTagCharacterStringBuilder) BACnetNameValueBuilder {
	builder := builderSupplier(b.Name.CreateBACnetContextTagCharacterStringBuilder())
	var err error
	b.Name, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetContextTagCharacterStringBuilder failed"))
	}
	return b
}

func (b *_BACnetNameValueBuilder) WithOptionalValue(value BACnetConstructedData) BACnetNameValueBuilder {
	b.Value = value
	return b
}

func (b *_BACnetNameValueBuilder) WithOptionalValueBuilder(builderSupplier func(BACnetConstructedDataBuilder) BACnetConstructedDataBuilder) BACnetNameValueBuilder {
	builder := builderSupplier(b.Value.CreateBACnetConstructedDataBuilder())
	var err error
	b.Value, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetConstructedDataBuilder failed"))
	}
	return b
}

func (b *_BACnetNameValueBuilder) Build() (BACnetNameValue, error) {
	if b.Name == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'name' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._BACnetNameValue.deepCopy(), nil
}

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

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

// CreateBACnetNameValueBuilder creates a BACnetNameValueBuilder
func (b *_BACnetNameValue) CreateBACnetNameValueBuilder() BACnetNameValueBuilder {
	if b == nil {
		return NewBACnetNameValueBuilder()
	}
	return &_BACnetNameValueBuilder{_BACnetNameValue: b.deepCopy()}
}

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

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

func (m *_BACnetNameValue) GetName() BACnetContextTagCharacterString {
	return m.Name
}

func (m *_BACnetNameValue) GetValue() BACnetConstructedData {
	return m.Value
}

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

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

func (m *_BACnetNameValue) GetTypeName() string {
	return "BACnetNameValue"
}

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

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

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

	return lengthInBits
}

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

func BACnetNameValueParse(ctx context.Context, theBytes []byte) (BACnetNameValue, error) {
	return BACnetNameValueParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func BACnetNameValueParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetNameValue, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetNameValue, error) {
		return BACnetNameValueParseWithBuffer(ctx, readBuffer)
	}
}

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

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

	name, err := ReadSimpleField[BACnetContextTagCharacterString](ctx, "name", ReadComplex[BACnetContextTagCharacterString](BACnetContextTagParseWithBufferProducer[BACnetContextTagCharacterString]((uint8)(uint8(0)), (BACnetDataType)(BACnetDataType_CHARACTER_STRING)), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'name' field"))
	}
	m.Name = name

	var value BACnetConstructedData
	_value, err := ReadOptionalField[BACnetConstructedData](ctx, "value", ReadComplex[BACnetConstructedData](BACnetConstructedDataParseWithBufferProducer[BACnetConstructedData]((uint8)(uint8(1)), (BACnetObjectType)(BACnetObjectType_VENDOR_PROPRIETARY_VALUE), (BACnetPropertyIdentifier)(BACnetPropertyIdentifier_VENDOR_PROPRIETARY_VALUE), (BACnetTagPayloadUnsignedInteger)(nil)), readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'value' field"))
	}
	if _value != nil {
		value = *_value
		m.Value = value
	}

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

	return m, nil
}

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

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

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

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

func (m *_BACnetNameValue) IsBACnetNameValue() {}

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

func (m *_BACnetNameValue) deepCopy() *_BACnetNameValue {
	if m == nil {
		return nil
	}
	_BACnetNameValueCopy := &_BACnetNameValue{
		utils.DeepCopy[BACnetContextTagCharacterString](m.Name),
		utils.DeepCopy[BACnetConstructedData](m.Value),
	}
	return _BACnetNameValueCopy
}

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