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

// BACnetConstructedDataSupportedFormats is the corresponding interface of BACnetConstructedDataSupportedFormats
type BACnetConstructedDataSupportedFormats interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	BACnetConstructedData
	// GetNumberOfDataElements returns NumberOfDataElements (property field)
	GetNumberOfDataElements() BACnetApplicationTagUnsignedInteger
	// GetSupportedFormats returns SupportedFormats (property field)
	GetSupportedFormats() []BACnetAuthenticationFactorFormat
	// GetZero returns Zero (virtual field)
	// TODO: uint 64 ---> big int in java == boom
	GetZero() uint64
	// IsBACnetConstructedDataSupportedFormats is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBACnetConstructedDataSupportedFormats()
	// CreateBuilder creates a BACnetConstructedDataSupportedFormatsBuilder
	CreateBACnetConstructedDataSupportedFormatsBuilder() BACnetConstructedDataSupportedFormatsBuilder
}

// _BACnetConstructedDataSupportedFormats is the data-structure of this message
type _BACnetConstructedDataSupportedFormats struct {
	BACnetConstructedDataContract
	NumberOfDataElements BACnetApplicationTagUnsignedInteger
	SupportedFormats     []BACnetAuthenticationFactorFormat
}

var _ BACnetConstructedDataSupportedFormats = (*_BACnetConstructedDataSupportedFormats)(nil)
var _ BACnetConstructedDataRequirements = (*_BACnetConstructedDataSupportedFormats)(nil)

// NewBACnetConstructedDataSupportedFormats factory function for _BACnetConstructedDataSupportedFormats
func NewBACnetConstructedDataSupportedFormats(openingTag BACnetOpeningTag, peekedTagHeader BACnetTagHeader, closingTag BACnetClosingTag, numberOfDataElements BACnetApplicationTagUnsignedInteger, supportedFormats []BACnetAuthenticationFactorFormat) *_BACnetConstructedDataSupportedFormats {
	_result := &_BACnetConstructedDataSupportedFormats{
		BACnetConstructedDataContract: NewBACnetConstructedData(openingTag, peekedTagHeader, closingTag),
		NumberOfDataElements:          numberOfDataElements,
		SupportedFormats:              supportedFormats,
	}
	_result.BACnetConstructedDataContract.(*_BACnetConstructedData)._SubType = _result
	return _result
}

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

// BACnetConstructedDataSupportedFormatsBuilder is a builder for BACnetConstructedDataSupportedFormats
type BACnetConstructedDataSupportedFormatsBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(supportedFormats []BACnetAuthenticationFactorFormat) BACnetConstructedDataSupportedFormatsBuilder
	// WithNumberOfDataElements adds NumberOfDataElements (property field)
	WithOptionalNumberOfDataElements(BACnetApplicationTagUnsignedInteger) BACnetConstructedDataSupportedFormatsBuilder
	// WithOptionalNumberOfDataElementsBuilder adds NumberOfDataElements (property field) which is build by the builder
	WithOptionalNumberOfDataElementsBuilder(func(BACnetApplicationTagUnsignedIntegerBuilder) BACnetApplicationTagUnsignedIntegerBuilder) BACnetConstructedDataSupportedFormatsBuilder
	// WithSupportedFormats adds SupportedFormats (property field)
	WithSupportedFormats(...BACnetAuthenticationFactorFormat) BACnetConstructedDataSupportedFormatsBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() BACnetConstructedDataBuilder
	// Build builds the BACnetConstructedDataSupportedFormats or returns an error if something is wrong
	Build() (BACnetConstructedDataSupportedFormats, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BACnetConstructedDataSupportedFormats
}

// NewBACnetConstructedDataSupportedFormatsBuilder() creates a BACnetConstructedDataSupportedFormatsBuilder
func NewBACnetConstructedDataSupportedFormatsBuilder() BACnetConstructedDataSupportedFormatsBuilder {
	return &_BACnetConstructedDataSupportedFormatsBuilder{_BACnetConstructedDataSupportedFormats: new(_BACnetConstructedDataSupportedFormats)}
}

type _BACnetConstructedDataSupportedFormatsBuilder struct {
	*_BACnetConstructedDataSupportedFormats

	parentBuilder *_BACnetConstructedDataBuilder

	collectedErr []error
}

var _ (BACnetConstructedDataSupportedFormatsBuilder) = (*_BACnetConstructedDataSupportedFormatsBuilder)(nil)

func (b *_BACnetConstructedDataSupportedFormatsBuilder) setParent(contract BACnetConstructedDataContract) {
	b.BACnetConstructedDataContract = contract
	contract.(*_BACnetConstructedData)._SubType = b._BACnetConstructedDataSupportedFormats
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) WithMandatoryFields(supportedFormats []BACnetAuthenticationFactorFormat) BACnetConstructedDataSupportedFormatsBuilder {
	return b.WithSupportedFormats(supportedFormats...)
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) WithOptionalNumberOfDataElements(numberOfDataElements BACnetApplicationTagUnsignedInteger) BACnetConstructedDataSupportedFormatsBuilder {
	b.NumberOfDataElements = numberOfDataElements
	return b
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) WithOptionalNumberOfDataElementsBuilder(builderSupplier func(BACnetApplicationTagUnsignedIntegerBuilder) BACnetApplicationTagUnsignedIntegerBuilder) BACnetConstructedDataSupportedFormatsBuilder {
	builder := builderSupplier(b.NumberOfDataElements.CreateBACnetApplicationTagUnsignedIntegerBuilder())
	var err error
	b.NumberOfDataElements, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetApplicationTagUnsignedIntegerBuilder failed"))
	}
	return b
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) WithSupportedFormats(supportedFormats ...BACnetAuthenticationFactorFormat) BACnetConstructedDataSupportedFormatsBuilder {
	b.SupportedFormats = supportedFormats
	return b
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) Build() (BACnetConstructedDataSupportedFormats, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._BACnetConstructedDataSupportedFormats.deepCopy(), nil
}

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

func (b *_BACnetConstructedDataSupportedFormatsBuilder) Done() BACnetConstructedDataBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewBACnetConstructedDataBuilder().(*_BACnetConstructedDataBuilder)
	}
	return b.parentBuilder
}

func (b *_BACnetConstructedDataSupportedFormatsBuilder) buildForBACnetConstructedData() (BACnetConstructedData, error) {
	return b.Build()
}

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

// CreateBACnetConstructedDataSupportedFormatsBuilder creates a BACnetConstructedDataSupportedFormatsBuilder
func (b *_BACnetConstructedDataSupportedFormats) CreateBACnetConstructedDataSupportedFormatsBuilder() BACnetConstructedDataSupportedFormatsBuilder {
	if b == nil {
		return NewBACnetConstructedDataSupportedFormatsBuilder()
	}
	return &_BACnetConstructedDataSupportedFormatsBuilder{_BACnetConstructedDataSupportedFormats: b.deepCopy()}
}

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

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

func (m *_BACnetConstructedDataSupportedFormats) GetObjectTypeArgument() BACnetObjectType {
	return 0
}

func (m *_BACnetConstructedDataSupportedFormats) GetPropertyIdentifierArgument() BACnetPropertyIdentifier {
	return BACnetPropertyIdentifier_SUPPORTED_FORMATS
}

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

func (m *_BACnetConstructedDataSupportedFormats) GetParent() BACnetConstructedDataContract {
	return m.BACnetConstructedDataContract
}

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

func (m *_BACnetConstructedDataSupportedFormats) GetNumberOfDataElements() BACnetApplicationTagUnsignedInteger {
	return m.NumberOfDataElements
}

func (m *_BACnetConstructedDataSupportedFormats) GetSupportedFormats() []BACnetAuthenticationFactorFormat {
	return m.SupportedFormats
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for virtual fields.
///////////////////////

func (m *_BACnetConstructedDataSupportedFormats) GetZero() uint64 {
	ctx := context.Background()
	_ = ctx
	numberOfDataElements := m.GetNumberOfDataElements()
	_ = numberOfDataElements
	return uint64(uint64(0))
}

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

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

func (m *_BACnetConstructedDataSupportedFormats) GetTypeName() string {
	return "BACnetConstructedDataSupportedFormats"
}

func (m *_BACnetConstructedDataSupportedFormats) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.BACnetConstructedDataContract.(*_BACnetConstructedData).getLengthInBits(ctx))

	// A virtual field doesn't have any in- or output.

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

	// Array field
	if len(m.SupportedFormats) > 0 {
		for _, element := range m.SupportedFormats {
			lengthInBits += element.GetLengthInBits(ctx)
		}
	}

	return lengthInBits
}

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

func (m *_BACnetConstructedDataSupportedFormats) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_BACnetConstructedData, tagNumber uint8, objectTypeArgument BACnetObjectType, propertyIdentifierArgument BACnetPropertyIdentifier, arrayIndexArgument BACnetTagPayloadUnsignedInteger) (__bACnetConstructedDataSupportedFormats BACnetConstructedDataSupportedFormats, err error) {
	m.BACnetConstructedDataContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("BACnetConstructedDataSupportedFormats"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for BACnetConstructedDataSupportedFormats")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	zero, err := ReadVirtualField[uint64](ctx, "zero", (*uint64)(nil), uint64(0))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'zero' field"))
	}
	_ = zero

	var numberOfDataElements BACnetApplicationTagUnsignedInteger
	_numberOfDataElements, err := ReadOptionalField[BACnetApplicationTagUnsignedInteger](ctx, "numberOfDataElements", ReadComplex[BACnetApplicationTagUnsignedInteger](BACnetApplicationTagParseWithBufferProducer[BACnetApplicationTagUnsignedInteger](), readBuffer), bool(bool((arrayIndexArgument) != (nil))) && bool(bool((arrayIndexArgument.GetActualValue()) == (zero))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'numberOfDataElements' field"))
	}
	if _numberOfDataElements != nil {
		numberOfDataElements = *_numberOfDataElements
		m.NumberOfDataElements = numberOfDataElements
	}

	supportedFormats, err := ReadTerminatedArrayField[BACnetAuthenticationFactorFormat](ctx, "supportedFormats", ReadComplex[BACnetAuthenticationFactorFormat](BACnetAuthenticationFactorFormatParseWithBuffer, readBuffer), IsBACnetConstructedDataClosingTag(ctx, readBuffer, false, tagNumber))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'supportedFormats' field"))
	}
	m.SupportedFormats = supportedFormats

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

	return m, nil
}

func (m *_BACnetConstructedDataSupportedFormats) 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 *_BACnetConstructedDataSupportedFormats) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("BACnetConstructedDataSupportedFormats"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for BACnetConstructedDataSupportedFormats")
		}
		// Virtual field
		zero := m.GetZero()
		_ = zero
		if _zeroErr := writeBuffer.WriteVirtual(ctx, "zero", m.GetZero()); _zeroErr != nil {
			return errors.Wrap(_zeroErr, "Error serializing 'zero' field")
		}

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

		if err := WriteComplexTypeArrayField(ctx, "supportedFormats", m.GetSupportedFormats(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'supportedFormats' field")
		}

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

func (m *_BACnetConstructedDataSupportedFormats) IsBACnetConstructedDataSupportedFormats() {}

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

func (m *_BACnetConstructedDataSupportedFormats) deepCopy() *_BACnetConstructedDataSupportedFormats {
	if m == nil {
		return nil
	}
	_BACnetConstructedDataSupportedFormatsCopy := &_BACnetConstructedDataSupportedFormats{
		m.BACnetConstructedDataContract.(*_BACnetConstructedData).deepCopy(),
		utils.DeepCopy[BACnetApplicationTagUnsignedInteger](m.NumberOfDataElements),
		utils.DeepCopySlice[BACnetAuthenticationFactorFormat, BACnetAuthenticationFactorFormat](m.SupportedFormats),
	}
	_BACnetConstructedDataSupportedFormatsCopy.BACnetConstructedDataContract.(*_BACnetConstructedData)._SubType = m
	return _BACnetConstructedDataSupportedFormatsCopy
}

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