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

// TraceContextDataType is the corresponding interface of TraceContextDataType
type TraceContextDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetTraceId returns TraceId (property field)
	GetTraceId() GuidValue
	// GetSpanId returns SpanId (property field)
	GetSpanId() uint64
	// GetParentSpanId returns ParentSpanId (property field)
	GetParentSpanId() uint64
	// GetParentIdentifier returns ParentIdentifier (property field)
	GetParentIdentifier() PascalString
	// IsTraceContextDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsTraceContextDataType()
	// CreateBuilder creates a TraceContextDataTypeBuilder
	CreateTraceContextDataTypeBuilder() TraceContextDataTypeBuilder
}

// _TraceContextDataType is the data-structure of this message
type _TraceContextDataType struct {
	ExtensionObjectDefinitionContract
	TraceId          GuidValue
	SpanId           uint64
	ParentSpanId     uint64
	ParentIdentifier PascalString
}

var _ TraceContextDataType = (*_TraceContextDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_TraceContextDataType)(nil)

// NewTraceContextDataType factory function for _TraceContextDataType
func NewTraceContextDataType(traceId GuidValue, spanId uint64, parentSpanId uint64, parentIdentifier PascalString) *_TraceContextDataType {
	if traceId == nil {
		panic("traceId of type GuidValue for TraceContextDataType must not be nil")
	}
	if parentIdentifier == nil {
		panic("parentIdentifier of type PascalString for TraceContextDataType must not be nil")
	}
	_result := &_TraceContextDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		TraceId:                           traceId,
		SpanId:                            spanId,
		ParentSpanId:                      parentSpanId,
		ParentIdentifier:                  parentIdentifier,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// TraceContextDataTypeBuilder is a builder for TraceContextDataType
type TraceContextDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(traceId GuidValue, spanId uint64, parentSpanId uint64, parentIdentifier PascalString) TraceContextDataTypeBuilder
	// WithTraceId adds TraceId (property field)
	WithTraceId(GuidValue) TraceContextDataTypeBuilder
	// WithTraceIdBuilder adds TraceId (property field) which is build by the builder
	WithTraceIdBuilder(func(GuidValueBuilder) GuidValueBuilder) TraceContextDataTypeBuilder
	// WithSpanId adds SpanId (property field)
	WithSpanId(uint64) TraceContextDataTypeBuilder
	// WithParentSpanId adds ParentSpanId (property field)
	WithParentSpanId(uint64) TraceContextDataTypeBuilder
	// WithParentIdentifier adds ParentIdentifier (property field)
	WithParentIdentifier(PascalString) TraceContextDataTypeBuilder
	// WithParentIdentifierBuilder adds ParentIdentifier (property field) which is build by the builder
	WithParentIdentifierBuilder(func(PascalStringBuilder) PascalStringBuilder) TraceContextDataTypeBuilder
	// 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 TraceContextDataType or returns an error if something is wrong
	Build() (TraceContextDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() TraceContextDataType
}

// NewTraceContextDataTypeBuilder() creates a TraceContextDataTypeBuilder
func NewTraceContextDataTypeBuilder() TraceContextDataTypeBuilder {
	return &_TraceContextDataTypeBuilder{_TraceContextDataType: new(_TraceContextDataType)}
}

type _TraceContextDataTypeBuilder struct {
	*_TraceContextDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (TraceContextDataTypeBuilder) = (*_TraceContextDataTypeBuilder)(nil)

func (b *_TraceContextDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._TraceContextDataType
}

func (b *_TraceContextDataTypeBuilder) WithMandatoryFields(traceId GuidValue, spanId uint64, parentSpanId uint64, parentIdentifier PascalString) TraceContextDataTypeBuilder {
	return b.WithTraceId(traceId).WithSpanId(spanId).WithParentSpanId(parentSpanId).WithParentIdentifier(parentIdentifier)
}

func (b *_TraceContextDataTypeBuilder) WithTraceId(traceId GuidValue) TraceContextDataTypeBuilder {
	b.TraceId = traceId
	return b
}

func (b *_TraceContextDataTypeBuilder) WithTraceIdBuilder(builderSupplier func(GuidValueBuilder) GuidValueBuilder) TraceContextDataTypeBuilder {
	builder := builderSupplier(b.TraceId.CreateGuidValueBuilder())
	var err error
	b.TraceId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "GuidValueBuilder failed"))
	}
	return b
}

func (b *_TraceContextDataTypeBuilder) WithSpanId(spanId uint64) TraceContextDataTypeBuilder {
	b.SpanId = spanId
	return b
}

func (b *_TraceContextDataTypeBuilder) WithParentSpanId(parentSpanId uint64) TraceContextDataTypeBuilder {
	b.ParentSpanId = parentSpanId
	return b
}

func (b *_TraceContextDataTypeBuilder) WithParentIdentifier(parentIdentifier PascalString) TraceContextDataTypeBuilder {
	b.ParentIdentifier = parentIdentifier
	return b
}

func (b *_TraceContextDataTypeBuilder) WithParentIdentifierBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) TraceContextDataTypeBuilder {
	builder := builderSupplier(b.ParentIdentifier.CreatePascalStringBuilder())
	var err error
	b.ParentIdentifier, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_TraceContextDataTypeBuilder) Build() (TraceContextDataType, error) {
	if b.TraceId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'traceId' not set"))
	}
	if b.ParentIdentifier == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'parentIdentifier' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._TraceContextDataType.deepCopy(), nil
}

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

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

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

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

// CreateTraceContextDataTypeBuilder creates a TraceContextDataTypeBuilder
func (b *_TraceContextDataType) CreateTraceContextDataTypeBuilder() TraceContextDataTypeBuilder {
	if b == nil {
		return NewTraceContextDataTypeBuilder()
	}
	return &_TraceContextDataTypeBuilder{_TraceContextDataType: b.deepCopy()}
}

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

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

func (m *_TraceContextDataType) GetExtensionId() int32 {
	return int32(19749)
}

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

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

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

func (m *_TraceContextDataType) GetTraceId() GuidValue {
	return m.TraceId
}

func (m *_TraceContextDataType) GetSpanId() uint64 {
	return m.SpanId
}

func (m *_TraceContextDataType) GetParentSpanId() uint64 {
	return m.ParentSpanId
}

func (m *_TraceContextDataType) GetParentIdentifier() PascalString {
	return m.ParentIdentifier
}

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

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

func (m *_TraceContextDataType) GetTypeName() string {
	return "TraceContextDataType"
}

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

	// Simple field (traceId)
	lengthInBits += m.TraceId.GetLengthInBits(ctx)

	// Simple field (spanId)
	lengthInBits += 64

	// Simple field (parentSpanId)
	lengthInBits += 64

	// Simple field (parentIdentifier)
	lengthInBits += m.ParentIdentifier.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	traceId, err := ReadSimpleField[GuidValue](ctx, "traceId", ReadComplex[GuidValue](GuidValueParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'traceId' field"))
	}
	m.TraceId = traceId

	spanId, err := ReadSimpleField(ctx, "spanId", ReadUnsignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'spanId' field"))
	}
	m.SpanId = spanId

	parentSpanId, err := ReadSimpleField(ctx, "parentSpanId", ReadUnsignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'parentSpanId' field"))
	}
	m.ParentSpanId = parentSpanId

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

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

	return m, nil
}

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

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

		if err := WriteSimpleField[uint64](ctx, "spanId", m.GetSpanId(), WriteUnsignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'spanId' field")
		}

		if err := WriteSimpleField[uint64](ctx, "parentSpanId", m.GetParentSpanId(), WriteUnsignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'parentSpanId' field")
		}

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

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

func (m *_TraceContextDataType) IsTraceContextDataType() {}

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

func (m *_TraceContextDataType) deepCopy() *_TraceContextDataType {
	if m == nil {
		return nil
	}
	_TraceContextDataTypeCopy := &_TraceContextDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[GuidValue](m.TraceId),
		m.SpanId,
		m.ParentSpanId,
		utils.DeepCopy[PascalString](m.ParentIdentifier),
	}
	_TraceContextDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _TraceContextDataTypeCopy
}

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